避免使用许多双查询到许多领域
问题描述:
在我的模型,我得到这个:避免使用许多双查询到许多领域
Model(models.Model):
prices = models.ManyToManyField('Price')
def foo(self):
obj_prices = self.prices.all() # I expect save all prices in 'obj_prices'
fist_price = obj_prices[0] # I need the first price
for obj_price in obj_prices: # Also I need to check each price
// Do something
正如我评论我希望保存所有价格“obj_prices”,以防止多个查询。但我用调试工具栏检查了这一点,我得到了这个:
SELECT ••• FROM `app_model` ASC LIMIT 1
SELECT ••• FROM `app_model` ASC
任何想法?谢谢。
答
QuerySets很懒,只在需要时执行。它试图通过仅对第一个查询执行LIMIT 1来帮助您。
如果你要遍历查询集反正,迫使其执行:
obj_prices = list(self.prices.all())