有没有一种方法可以从带有外键的模型中选择一些特定字段。这是一个例子: 假设我有
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的新手,可以在文档中找到它)
谢谢
是的,您可以使用以下示例进行查询:
The
Order
objects that arise from this queryset, will have two extra attribute.product_name
and.product_price
that contains thename
and theprice
of te relatedProduct
.In the
Order
object itself, you can just useself.product.name
. You already do that, for example in the__str__
method. You can for example fetch thename
andprice
of the relatedproduct
with: