繁体   English   中英

Django 查询集外键 3 个表

[英]Django queryset foreign key 3 tables

我有以下型号:

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)

我需要从 Orden 一直查询到 Productos 并获取“名称”属性

我尝试了以下方法:

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

我得到 Id 而不是“nombre”:

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

如何从“Productos”Model 访问属性“nombre”?

您应该像这样categoria = Orden.objects.filter(user=self.request.user, ref_code = '225v3cwhvqi0ymp2yw2n').values('producto__producto__nombre')查询

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM