Django Query Related Field Count

Brenden picture Brenden · Jun 29, 2011 · Viewed 29.7k times · Source

I've got an app where users create pages. I want to run a simple DB query that returns how many users have created more than 2 pages.

This is essentially what I want to do, but of course it's not the right method:

User.objects.select_related('page__gte=2').count()

What am I missing?

Answer

Ismail Badawi picture Ismail Badawi · Jun 29, 2011

You should use aggregates.

from django.db.models import Count
User.objects.annotate(page_count=Count('page')).filter(page_count__gte=2).count()