无法使用ann获取最大值

2024-09-29 23:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是模型.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

这是视图.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()

annotate查询返回如下结果

[30L, 20L, 40L]

我想在这里是,它应该返回最大的折扣..但它抛出了多个结果,如20L,30L,40L

我该怎么做才能得到折扣的最大值

谢谢你


Tags: storepytrueobjectsmodelsdiscountproductitem
1条回答
网友
1楼 · 发布于 2024-09-29 23:21:26

您应该使用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)

相关问题 更多 >

    热门问题