Django Query Related Field Count
Asked Answered
F

3

79

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?

Fable answered 29/6, 2011 at 18:57 Comment(0)
T
149

You should use aggregates.

from django.db.models import Count
User.objects.annotate(page_count=Count('page')).filter(page_count__gte=2).count()
Tomi answered 29/6, 2011 at 19:5 Comment(1)
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"'))Anonymous
P
5

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)
Passel answered 24/6, 2017 at 5:59 Comment(0)
L
0

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"))
Lucialucian answered 3/4, 2021 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.