我正在尝试减少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)
Prefetch无法正常运行,我不知道该如何使用..请帮助。
我的数据库中有31种产品,而django_debug_tool的结果为35个查询。
答案 0 :(得分:1)
仅为您感兴趣的客户预取CustomerProducts
,然后使用该结果。像这样:
products = Product.objects.all().prefetch_related(
models.Prefetch(
'customerproduct_set',
queryset=CustomerProduct.objects.filter(customer=customer, deleted=0).order_by('id')
to_attr='customer_prices'
)
)
def get_product_prices(product):
customer_prices = getattr(product, 'customer_prices', None)
if customer_prices:
return customer_prices[-1].price
return product.price
for product in products:
print get_product_prices(product)