【发布时间】:2018-10-29 07:45:21
【问题描述】:
我正在尝试减少 Django 应用程序中的查询量,但不知道如何以正确的方式进行。我有一个产品模型,所有产品都有默认价格,现在我有一个客户产品,其中包含一些与客户相关的产品价格
我愿意重新设计 ;)
class Product(models.Model)
name = models.CharField(max_length=255)
price = models.DecimalField(default=0, max_digits=12, decimal_places=2)
....
def get_prices(self, customer=None):
'''
get prices for the current product based on the price matrix given by bbp
'''
if customer:
prices = self.get_customer_prices()
if prices:
self.price = self.customerproduct_set.filter(deleted=0).last().price
return self
class CustomerProduct(AbstractProductPrice):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.DecimalField(default=0, max_digits=12, decimal_places=2)
....
现在我想要所有具有相关客户价格的产品。
products = Product.objects.all().prefetch_related('customerproduct_set')
for product in products:
product.get_prices(customer=1)
预取不“工作”我不明白如何使用它..请帮助。
我的数据库中有 31 个产品,django_debug_tool 产生 35 个查询。
【问题讨论】:
-
你
filtercustomerproduct_set,一个简单的.prefetch_related只能获取“.all()”可以这么说。但是,您可以构造一个Prefetch(..)对象,该对象可以预取过滤集。 -
哇,我没听懂,你能给我举个例子吗? ;)
-
但是这里有什么奇怪的地方吗?您查询
.last()?但是您没有定义订单,这意味着它可以返回任何 (?)CustomerProduct具有deleted=0?
标签: django django-models