django:在带有注释的Sum函数中使用if else或while else吗?无法计算Sum('<CombinedExpression:..')是一个聚合

art_cs:

我想在我的Sum函数中设置一个条件,annotate我尝试使用Case When但在我的情况下却不起作用

这是我的models.py

class MyModel(models.Model):
    name = models.ForeignKey(Product, on_delete=models.CASCADE)
    order = models.IntegerField()
    price = models.IntegerField()

class Prodcut(models.Model):
    name = models.CharField(max_lenth=20)
    cost = models.IntegerField()
    price = models.IntegerField()

我想要这样的事情

total = F('price')*F('order')
base = (F(name__cost')+F('name__price')) * F('order')
if  total> base:
    income = Sum(F('total') - F('base'))

我尝试了这个

MyModel.objects.values('name__name').annotate(total=(Sum(F('price') * F('order'),output_field=IntegerField())),
                        base=(Sum((F('name__price')+F('name__cost'))*F('order'),output_field=IntegerField())
                            ),
                        income=Sum(
                            Case(When(total__gt=F('base') , then=Sum(F('total') - F('base'))),default=0),output_field=IntegerField()),)

但这会引发此错误:

无法计算Sum('<CombinedExpression:F(total)-F(base)>'):'<< CombinedExpression:F(total)-F(base)>'是一个聚合

我不想使用,.filter(income__gt=0)因为它停止quantity计数了,我也不想指望income那些失去其销量的产品

MyModel(name=mouse ,order=2,price=20)在产品模型上发表文章,并在我的产品模型中找到了有关鼠标产品的这些信息Product(name=mouse,cost=4,price=10),当我计算发现该产品的收入(2 *20) - ((4+10)*2) => 40 - 28 = 12时:(2*10) - ((4+10)*2) => 20 - 28 = -8

*我将mysql v:8用于数据库

我想防止负数添加到我income关于其他列quantity

亚历山大·塔塔里诺夫(Alexander Tatarinov):

问题是您不能在同一查询的另一个聚合中使用聚合(总计和基数)。只有一个GROUP BY子句,并且Django无法在此处自动生成有效的查询。据我了解,您需要首先计算总数和基数,找到每个MyModel的收入,然后才产生一个合计:

MyModel.objects.annotate(
    total=F('price') * F('order'),
    base=(F('name__price') + F('name__cost')) * F('order'),
    income=Case(
        When(total__gt=F('base'), then=F('total') - F('base')),
        default=0,
        output_field=IntegerField()
    )
).values('name__name').annotate(income=Sum('income'))

附言:请格式化您的代码,以便人们可以轻松阅读它:)

PPS我可能会看到另一种方式,您不需要Sum()作为收入,因为总数和基数已经是总数

MyModel.objects.values('name__name').annotate(
    total=Sum(F('price') * F('order')),
    base=Sum((F('name__price') + F('name__cost')) * F('order')),
).annotate(
    income=Case(
        When(total__gt=F('base'), then=F('total') - F('base')),
        default=0,
        output_field=IntegerField()
    )
)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章