Skip to main content
 首页 » 编程设计

python之如何在 Django ORM 中连接两个表而没有第一个表中的任何列引用第二个

2024年11月24日25dflying

检查下面的模型

现在我想加入表格并获取产品名称和价格

我无法加入表格,因为我在产品模型中没有引用价格模型的列

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() 

请您参考如下方法:

您可以使用 .select_related(...)在 Price 模型上,例如:

prices = Price.objects.<b>select_related('product')</b>

例如,您可以对其进行迭代,并打印产品名称和价格,例如:

for price in prices: 
    print('{}: {}'.format(price.product.name, price.price))

或者您可以使用 .annotate(...)从相关模型中获取字段,例如:

from django.db.models import F 
 
products = Product.objects.annotate(price=<b>F('price__price')</b>)

然后打印:

for product in products: 
    print('{}: {}'.format(product.name, product.price))

终于可以了 .prefetch_related(...) Price,然后遍历这些,例如:

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 中。