python - Custom aggregate annotation in Django -
i have many groups each has revision , each revision has months.
i want output grouping objects annotation.
for each grouping should select latest revision , sum months.
i'm not sure if can done in django. tried like
group.objects.annotate( month_sum=revision.objects.filter(date__lte=my_date).latest('date').aggregate(sum('months__amount')) )
and hoped queryset groups each has sum month_sum
.
can seek one:
qs = group.objects.filter(revision__date__lte=my_date).annotate(month_sum=sum('months__amount'))
you can debug , seek undestand how create right query printing generated db query in shell:
print str(qs.query)
edit:
to show groups old revision think django-aggregate-if may help you
run pip install django-aggregate-if
from django.db.models import q aggregate_if import sum revision = revision.objects.filter(revision__date__lte=my_date).latest() qs = group.objects.all().annotate(month_sum=sum('months__amount', only=q(revision=revision)))
python django django-models django-views django-queryset
No comments:
Post a Comment