0
功能的一部分是计算最后一个有效报价的数量,它们低于,等于和高于a_price
。无法找出更好的方法,因此我现在使用两个循环。问题是这会执行575个太多的查询。如何减少嵌套循环中的查询数(575)?
一个产品可以有很多买家和买家有很多优惠(具有不同的日期)。我试图添加prefetch_related('buyers')
但它根本没有帮助。
编辑:在这种情况下,有32个产品,每个产品有0到30个买家。
reset_queries()
products = Product.objects.filter(user=user)
my_active_products = products.filter(active=True).prefetch_related('buyers')
for product in my_active_products:
for buyer in product.buyers.filter(valid=True):
last_valid_offer = buyer.get_last_valid_offer()
a_price = product.a_price
if a_price:
if a_price < last_valid_offer.eur_price:
cheaper += 1
elif a_price > last_valid_offer.eur_price:
more_expensive += 1
elif a_price == last_valid_offer.eur_price:
equal += 1
else:
unknown += 1
print len(connection.queries)
你知道我应该怎么做才能减少查询次数?
编辑Models.py:
class Product(Model):
name...
active = BooleanField(...)
class Buyer(Model):
product = ForeignKey('Product',related_name='buyers')
def get_last_valid_offer(self):
return self.offers.filter(valid=True).latest('datetime')
class Offer(Model):
buyer = ForeignKey('Buyer', related_name='offers')
valid = BooleanField(...)
datetime = DateTimeField(...)
eur_price = MoneyField(...)
谢谢。我的模式看起来有点不同。我已经从models.py中添加了一个非常简化的模型,直到问题的底部。买方表中没有'last_offer'属性。我计算它像buyer.offers.latest('datetime')。 –
添加了查询的django翻译,我没有对它进行测试,所以它肯定会在某个地方出现:D但它的价值更多是为了了解django文档的哪些部分。 – qwattash