Can I execute a custom complex group in a Django QuerySet?

I need to make the sum of a specific column, grouped by date and month. In SQL (postgres), it will look something like this:

select sum(amount) from somewhere group by extract(year from date), extract(month from date)

Can this be expressed as Django QuerySet? I don't seem to like this, but I really don't want to resort to plain old SQL. Any other ideas are welcome.

It seems like it's possible using queryset.query.group_by, but I was out of luck - a working example would be welcome.

+3
source share
2 answers

You can use the method extrato add year and date values ​​before performing aggregation.

Somewhere.objects.extra(select={'year': 'EXTRACT(year FROM date)',
                                'month': 'EXTRACT(month FROM date)'}
                       ).values_list('year', 'month').annotate(Sum('amount'))
+8
source
+1

Source: https://habr.com/ru/post/1786105/


All Articles