简体   繁体   English

Django 将正值与负值分开

[英]Django Sum positive values separate from negative values

Can you sum positive values separately from negative values?您可以将正值与负值分开求和吗?

I have a table that looks like this:我有一个看起来像这样的表:

class Order(models.Model):
    date = models.DateField()
    amount = models.DecimalField()

I'm looking to get a queryset that sums the postive amounts seperate from the negative amounts and groups by week:我正在寻找一个查询集,它按周将正金额与负金额和组分开:

Year
Week
Sum of positive amounts
Sum of negative amounts

I'm able to get all positive amounts per week seperately by doing:我可以通过以下方式每周分别获得所有正数:

Order.objects.filter(amount__gt=0).annotate(year_week=Trunc('date', 'week', output_field=DateField())).\
annotate(year=ExtractYear('year_week')).annotate(week=ExtractWeek('year_week')).\
values("year_week", "year", "week").annotate(value=Sum("amount")).order_by("-year_week")

I can do this again for the negative value, but then I have two seperate querysets.我可以为负值再次执行此操作,但是我有两个单独的查询集。 Can I merge them efficiently without looping manually or is there a way to do both in a single query?我可以在不手动循环的情况下有效地合并它们吗?或者有没有办法在一个查询中同时完成这两者?

Yes, since , most aggregate functions have afilter=… parameter [Django-doc] :是的,从,大多数聚合函数都有一个filter=…参数 [Django-doc]

from django.db.models import Q, Sum
from django.db.models.functions import ExtractYear, ExtractWeek

Order.objects.values(
    year=ExtractYear('date'),
    week=ExtractWeek('date')
).annotate(
    sum_pos=Sum('amount', filter=Q(amount__gt=0)),
    sum_neg=Sum('amount', filter=Q(amount__lt=0))
).order_by('year', 'week')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM