【问题标题】:How to join two tables in Django ORM without any column in first table referencing the second如何在 Django ORM 中连接两个表,而第一个表中没有任何列引用第二个表
【发布时间】:2019-11-28 08:30:30
【问题描述】:

查看以下型号

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

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

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 模型,尤其是因为您的price 字段只是对Product 模型的引用?如果一个产品有多个价格,关系可能应该命名为product = ...,并且你应该添加一个price = ... 列(包含该产品的价格,例如在特定国家/地区)
  • @WillemVanOnsem 我的错,它是 product = models.ForeignKey(Product), Price = models.IntegerField()

标签: python django python-3.x python-2.7 django-models


【解决方案1】:

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

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=F('price__price'))

然后打印出来:

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

最后你可以.prefetch_related(...)Prices,然后遍历这些,比如:

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 则为空价格怎么办
  • @Peekay:那么你可以使用后者,因为那时price 将是None。
  • @Peekay: 或者你可以遍历.price_set,但是使用.prefetch_related会在性能上更好。
猜你喜欢
  • 2021-08-23
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
相关资源
最近更新 更多