Django Query Related Field Count

35,018

Solution 1

You should use aggregates.

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

Solution 2

In my case, I didn't use last .count() like the other answer and it also works nice.

from django.db.models import Count

User.objects.annotate( our_param=Count("all_comments")).filter(our_param__gt=12)
Share:
35,018
Brenden
Author by

Brenden

Updated on July 05, 2022

Comments

  • Brenden
    Brenden almost 2 years

    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?

  • Rmatt
    Rmatt almost 11 years
    is it possible to combine (since I need it as a queryset for my admin) one annotation Counting the occurence of a related element and an annotation Counting the elements matching an exact value ? The following doesn't work for me: super(ModelAdmin, self).queryset(request ).annotate(o_count=Count('v__g_o') ).annotate(timedout_o_count=Count('v__g_o__d_t__exact="AUTO_‌​DECLINE"'))