2014-09-25 65 views
0

在我的模型,我得到這個:避免使用許多雙查詢到許多領域

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 

任何想法?謝謝。

回答

0

QuerySets很懶,只在需要時執行。它試圖通過僅對第一個查詢執行LIMIT 1來幫助您。

如果你要遍歷查詢集反正,迫使其執行:

obj_prices = list(self.prices.all())