2016-05-30 72 views
0

這裏是models.py無法使用註釋

class StoreProduct(models.Model): 
    product = models.ForeignKey('products.Product') 
    category = models.ForeignKey('products.Category') 
    store = models.ForeignKey('Store') 
    price = models.IntegerField(null=True , blank=True) 
    quantity = models.IntegerField(null=True , blank=True) 
    discount = models.IntegerField(null=True , blank=True) 
    size = models.CharField(max_length=50 , null=True , blank=True) 
    color = models.CharField(max_length=50 , null=True , blank=True) 
    timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) 

    objects = StoreProductManager() 


    def __unicode__(self): 
     return self.product.title 

這裏獲得最大的價值是views.py

if discount: 
       max_discount = StoreProduct.objects.filter(product=item).values_list('discount' , flat=True).annotate(Max('discount')) 
       min_price_store = StoreProduct.objects.filter(product=item , discount=max_discount).values_list('store__StoreName' , flat=True) 

       print max_discount, min_price_store 

       if discount > max_discount: 
        item.discount = discount 
        item.save() 

的註釋查詢返回結果這樣

[30L, 20L, 40L] 

我想在這裏是它應該返回最大折扣..但它是投擲多個結果,如20L,30L,40L。

我能做些什麼來獲得折扣的最大值?

謝謝。

+0

有問題您的查詢是,您目前正在嘗試按「折扣」字段進行分組,然後查找每個組的「Max()」,這基本上會將不同的折扣返回給您。正確的方法是使用'aggregate()'。 –

+0

@Aditya你有沒有得到關於這個職位的答案http://stackoverflow.com/q/37550364/4099593?你可以在聊天室詢問http://chat.stackoverflow.com/rooms/6/python但是我不知道你是否可以在那裏說話。 –

+0

不,我沒有得到它,加上我得到負面評論,所以我刪除了它@BhargavRao –

回答

2

你應該使用aggregate作爲annotate只增加了對象查詢

storeproduct = StoreProduct.objects.filter(product=item).aggregate(max_discount=Max('discount')) 

storeproduct['max_discount']將返回最高優惠價值,並能在你的下一個查詢中使用像這樣:

min_price_store = StoreProduct.objects.filter(product=item , discount=storeproduct['max_discount']).values_list('store__StoreName' , flat=True) 
+0

第二個查詢返回多個結果...它應該返回商店最大折扣 –

+0

如果有多個商店與最大折扣價值? –

+0

它顯示像這樣{'max_discount':40} ....我如何得到我的價值? –