有没有一种方法可以从Django模型中选择特定字段?

有没有一种方法可以从带有外键的模型中选择一些特定字段。这是一个例子: 假设我有

class Product(models.Model):
    CATEGORY = (
            ('A', 'A'),
            ('B', 'B'),
            ('C', 'C'),
            )
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField(null=True)
    category = models.CharField(max_length=200, null=True, choices=CATEGORY)
    description = models.CharField(max_length=200, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.name

class Order(models.Model):
    STATUS = (
            ('Work Under Progress', 'Work Under Progress'),
            ('Delivered', 'Delivered'),
            )

    product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=200, null=True, 
        choices=STATUS) 
    def __str__(self):
        return self.product.name

目的是在Order类中获取产品名称和产品价格。 有什么办法吗? (我是Django的新手,可以在文档中找到它)

谢谢

评论
  • 仵灵波
    仵灵波 回复

    是的,您可以使用以下示例进行查询:

    from django.db.models import F
    
    orders = Order.objects.annotate(
        product_name=F('product__name'),
        product_price=F('product_price')
    )

    The Order objects that arise from this queryset, will have two extra attribute .product_name and .product_price that contains the name and the price of te related Product.

    In the Order object itself, you can just use self.product.name. You already do that, for example in the __str__ method. You can for example fetch the name and price of the related product with:

    class Order(models.Model):
        STATUS = (
                ('Work Under Progress', 'Work Under Progress'),
                ('Delivered', 'Delivered'),
                )
    
        product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
        date_created = models.DateTimeField(auto_now_add=True)
        status = models.CharField(max_length=200, null=True, 
            choices=STATUS) 
        def __str__(self):
            if self.product_id is not None:
                return '{}: {}'.format(self.product.name, self.product.price)
            else:
                return 'no_product'