Django admin queryset foreign key to user django-allauth

I have an e-commerce development and I'm looking to send an email to the client from the admin site, I can´t the queryset correclty to do this. I have the following model:

models.py:

class Orden(models.Model):
    cliente = models.ForeignKey(
        User, on_delete=models.CASCADE, verbose_name='Usuario')
    productos = models.ManyToManyField(OrdenProducto)
    fecha_orden = models.DateTimeField(auto_now_add=True)
    completada = models.BooleanField(default=False, null=True, blank=True)
    id_transaccion = models.CharField(max_length=20, null=True)
    correo_enviado = models.BooleanField(default=False, null=True, blank=True)
    datos_pedido = models.ForeignKey(
        'DatosPedido', on_delete=models.SET_NULL, blank=True, null=True)
    pago = models.ForeignKey(
        'Pago', on_delete=models.SET_NULL, blank=True, null=True)
    cupon = models.ForeignKey(
        'Cupon', on_delete=models.SET_NULL, blank=True, null=True)

    class Meta:
        verbose_name_plural = "Orden"

    def __str__(self):
        return self.cliente.username

cliente has a foreign key to the User model and I want to get the email address, I have tried many ways but I just can´t get it.

admin.py:

class OrdenAdmin(admin.ModelAdmin):
    list_display = ('cliente', 'completada', 'correo_enviado')
    actions = ['enviar_correo']

    def enviar_correo(self, request, queryset):
        queryset.update(correo_enviado=True)
        a = queryset.get(cliente=self.user.email)

        send_mail('test', 'test', '[email protected]',
                  ['a], fail_silently=True)

Answers 1

  • You can try iterating the queryset to access the specific data in the rows.

    Try the following code.

    class OrdenAdmin(admin.ModelAdmin):
        list_display = ('cliente', 'completada', 'correo_enviado')
        actions = ['enviar_correo']
    
        def enviar_correo(self, request, queryset):
            queryset.update(correo_enviado=True)
            for obj in queryset:
                email = obj.cliente.email
    
            send_mail('test', 'test', email,
                      ['a], fail_silently=True)
    

    I hope this code helps you


Related Articles