Python 如何在Django ORM中连接两个表,而第一个表中没有任何列引用第二个表
检查下面的模型 现在我想加入这些表并获得产品名称和价格 我无法联接这些表,因为我在产品模型中没有引用价格模型的列Python 如何在Django ORM中连接两个表,而第一个表中没有任何列引用第二个表,python,django,python-3.x,python-2.7,django-models,Python,Django,Python 3.x,Python 2.7,Django Models,检查下面的模型 现在我想加入这些表并获得产品名称和价格 我无法联接这些表,因为我在产品模型中没有引用价格模型的列 class Product(models.Model): name = models.CharField(max_length=100) class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.Intege
class Product(models.Model):
name = models.CharField(max_length=100)
class Price(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.IntegerField()
您可以在Price
型号上使用,如:
prices = Price.objects.select_related('product')
from django.db.models import F
products = Product.objects.annotate(price=F('price__price'))
也可以使用从相关模型中获取字段,如:
prices = Price.objects.select_related('product')
from django.db.models import F
products = Product.objects.annotate(price=F('price__price'))
最后,您可以选择Price
s,然后对其进行迭代,如:
products = Product.objects.prefetch_related('price_set')
for product in products:
prices = product.price_set.all()
if prices:
for price in prices:
print('{}: {}'.format(product.name, price.price))
else:
print('No prices for {}'.format(product.name))
也就是说,如果价格不随时间、国家等发生变化,那么最好将价格存储在
产品中为什么要在此处添加价格模型,尤其是因为价格字段只是对产品模型的引用?如果一个产品有多个价格,那么这个关系可能应该命名为product=…
,并且您应该添加一个price=…
列(带有该产品的价格,例如在特定国家的价格)@WillemVanOnsem my bad,它是product=models.ForeignKey(product),price=models.IntegerField()我也尝试过这个方法。但这种方法的问题在于,它只会给出有价格细节的产品的细节。如果我想要所有的产品,如果没有空的价格怎么办Price@Peekay:然后您可以使用后者,因为price
将是None
@Peekay:或者您可以迭代.price\u集
,但是使用.prefetch\u related
性能更好。