I need to do a sum of a certain column grouped by date and month. In SQL (postgres), it would look something like this:
select sum(amount) from some开发者_如何学Gowhere group by extract(year from date), extract(month from date)
Can this be expressed as a Django QuerySet
? Seems to me like it can't, but I don't really want to resort to plain old SQL. Any other ideas are welcome.
Seems like it might be possible using queryset.query.group_by
, but I haven't had any luck with that - a working example would be welcome.
You can use the extra
method to add in the year and date values before doing the aggregation.
Somewhere.objects.extra(select={'year': 'EXTRACT(year FROM date)',
'month': 'EXTRACT(month FROM date)'}
).values_list('year', 'month').annotate(Sum('amount'))
Take a look at Complex lookups with Q objects and Generating aggregates for each item in a QuerySet.
精彩评论