djangodjango-querysetdjango-select-related

Django Query Related Field Count


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?


Solution

  • You should use aggregates.

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