Django Query Related Field Count

Viewed 36997

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?

3 Answers

use aggregate() function with django.db.models methods! this is so useful and not really crushing with other annotation aggregated columns. *use aggregate() at the last step of calculation, it turns your queryset to dict.

below is my code snippet using them.

cnt = q.values("person__year_of_birth").filter(person__year_of_birth__lte=year_interval_10)\
               .filter(person__year_of_birth__gt=year_interval_10-10)\
               .annotate(group_cnt=Count("visit_occurrence_id")).aggregate(Sum("group_cnt"))
Related