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