Django models - how to properly calculate multiple values with various conditions

I want to calculate multiple values in a single query on my model. each metric should have a different filter (or no filters at all) I'm using Django==2.2.3 and a Djongo model.

MyModel columns:

user_id  = models.IntegerField(blank=True, null=True)
group_id = models.IntegerField(blank=True, null=True)

What i try to run, suggested in another topic, does not work for me. Query:

MyModel.objects.aggregate
    (
        total=Count('user_id'), 
        test=Count('user_id', filter=Q(user_id='just_a_fake_id')),
        group_1_value=Count('user_id', filter=Q(group_id=1)),
        group_2_value=Count('user_id', filter=Q(group_id=2)),     
 ) 

The results: {'total': 0, 'test': 47479, 'group_1_value': 47479, 'group_2_value': 47479}, does not make sense - all results (except total) returns the same number which is the count of all the records

What i want to run is query similar to

SELECT COUNT(user_id) as total,
       COUNT(CASE WHEN group_id=1 THEN user_id END) as group_1_value,
       COUNT(CASE WHEN group_id=2 THEN user_id END) as group_2_value
FROM MyModel

How do i need to modify the query in order to get the correct values?

Back to Top