Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django ORM中连接两个表,而第一个表中没有任何列引用第二个表_Python_Django_Python 3.x_Python 2.7_Django Models - Fatal编程技术网

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
性能更好。