[Answered ]-Django Really Simple Aggregation (or Group By)

1👍

I blogged about this very issue a couple of years ago. Contrary to the other answers, it’s perfectly possible in Django, with no need for raw SQL.

1👍

Django’s annotations allow you to attach some basic calculations to each object in your queryset (or aggregations across the entire queryset) but you can’t filter those annotations (i.e. in your case, you only want to count thoseusers who share your name)

Django also has F() objects which allow you to use a fields value within a query. Ideally you could use these in conjunction with annotations to filter the objects you are annotation, but that’s not currently possible (there’s a fix on the way)

So, an easy solution is to perform the annotation manually:

users = User.objects.all().extra(select={
    'same_name_count' : """
    SELECT COUNT(*)
    FROM auth_user
    WHERE auth_user.first_name = user.first_name
    """
})

0👍

Check this: https://docs.djangoproject.com/en/dev/topics/db/aggregation/

from django.db.models import Count
auth_user.objects.annotate(num_users=Count('first_name'))

For more complex queries you can use plain SQL but try to avoid it.

UPD Code fixed. Thanks Timmy O’Mahony for mention!

👤power

Leave a comment