Home > Software engineering >  Django queryset foreign key 3 tables
Django queryset foreign key 3 tables

Time:10-01

I have the following models:

class Productos(models.Model):
   
    nombre = models.CharField(max_length=200, null=True)
    precio_publico = models.FloatField(null=True, blank=True)
    costo = models.FloatField(null=False, blank=False)
    inventario = models.IntegerField(null=False, blank=False, default=0)
    fecha_compra = models.DateField(blank=True, null=True)
    tipo_movimiento = models.CharField(max_length=1, choices=TIPO_MOVIMIENTO)
    slug = models.SlugField(blank=True, null=True)
    descripcion_corta = models.TextField(blank=True, null=True)
    descripcion = models.TextField(blank=True, null=True)
    imagen = models.ImageField(upload_to='images/',blank=True, null=True)
    marca = models.CharField(max_length=20)
    categoria = models.ForeignKey(Categorias, null= True, on_delete=SET_NULL)
    descuento = models.ForeignKey(Promos, blank=True, null=True, on_delete=CASCADE)
    inventariar = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class ProductosOrden(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    producto = models.ForeignKey(Productos, on_delete=models.CASCADE)
    cantidad = models.IntegerField(default=1)
    ordenado = models.BooleanField(default=False)

class Orden(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    producto = models.ManyToManyField(
        ProductosOrden)
    medio_de_venta = models.ForeignKey(MediosVenta, null=True, blank=False, on_delete=models.SET_NULL)
    fecha_venta = models.DateField(blank=False, null=False)
    ordenado = models.BooleanField(default=False)
    ref_code = models.CharField(max_length=20, blank=True, null=True)
    promo = models.ForeignKey(Promos,null=True, blank=True, on_delete=CASCADE )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    vendido_por = models.CharField(max_length=20, null=False, blank=False)

I need to query from Orden all the way to Productos and get the 'name' attribute

I have tried the following:

categoria = Orden.objects.filter(user=self.request.user, ref_code = '225v3cwhvqi0ymp2yw2n').values('producto__producto')

and I get Id's instead of 'nombre':

<QuerySet [{'producto__producto': 5}, {'producto__producto': 19}, {'producto__producto': 3}]>

how can I access the attribute 'nombre' from the 'Productos' Model?

CodePudding user response:

You should build query like this categoria = Orden.objects.filter(user=self.request.user, ref_code = '225v3cwhvqi0ymp2yw2n').values('producto__producto__nombre')

  • Related