How to Aggregate + Count?

Well, I’d like to make an aggregation, which is a simple sum of a price field and also count the elements on the same queryset. So initially I did this:

total_sum = my_queryset.aggregate(
   total_sum=Sum('price', filter=Q(...)),
)

total_count = my_queryset.filter(...).count()

The problem is that’s not very performatic, so I needed them to be a single query. Just like

SELECT COUNT(*), SUM(price) FROM ... WHERE ...

But when I do this:

total_sum = my_queryset.aggregate(
   total_sum=Sum('price', filter=Q(...)),
   total_count=Count('price', filter=Q(...)),
)

total_count returns always 0. Am I missing something?

Assuming those two filter clauses are the same, I’d try applying the filter on the queryset and then aggregating the results of the filtered data.

e.g.,

totals = my_queryset.filter(...).aggregate(
    total_sum=Sum('price'), 
    total_count=Count('price')
)

Note: I’m winging this, so I’m not sure this is right, but this is where I’d be starting to try things.