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)
您看过使用该.extra()方法吗?
请参阅Django 查询集 API。
| 归档时间: |
|
| 查看次数: |
17587 次 |
| 最近记录: |