2016-05-30 50 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} ....我如何得到我的价值? –