注释两个字段的总和相乘

Sam*_*Sam 36 django django-models

我有三个模型,简化为例子:

class Customer(models.Model):
    email = models.CharField(max_length=128)

class Order(models.Model):
    customer = models.ForeignKey(Customer)
    order_status = models.CharField(blank=True, max_length=256)

class Lineitem(models.Model):
    order = models.ForeignKey(Order)
    quantity = models.IntegerField(blank=True)
    price = models.DecimalField(max_digits=6, decimal_places=2)
Run Code Online (Sandbox Code Playgroud)

我想查询客户(可能使用过滤器)并注释他们花费的总额(即总和(价格*数量))

我试过了:
Customer.objects.filter(something).annotate(total_spent=Sum(F('order__lineitem__quantity') * F('order__lineitem__price')))

似乎Sum()不能与F()表达式一起使用.还有另一种方法吗?

小智 11

也许你现在不需要这个答案,但如果你阅读有关Sum表达式的文档,你需要声明output_field,如下所示:

Customer.objects.filter(something)
                .annotate(total_spent=Sum(
                    F('order__lineitem__quantity') * 
                    F('order__lineitem__price'),   
                    output_field=models.FloatField()
                ))
Run Code Online (Sandbox Code Playgroud)


Gra*_*ant 1

您看过使用该.extra()方法吗?

请参阅Django 查询集 API

  • 我有。它有效,但我试图避免它有两个原因:首先,它使用每行子查询而不是联接,这对于某些数据库后端来说可能会严重扩展。其次,它不能与额外字段上的 filter() 一起使用,因此它不能在程序上与其他 Q 对象组合 (3认同)