Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 918
Brenden Avatar asked Jun 29 '11 18:06

Brenden


2 Answers

You should use aggregates.

from django.db.models import Count
User.objects.annotate(page_count=Count('page')).filter(page_count__gte=2).count()
like image 157
Ismail Badawi Avatar answered Nov 13 '22 14:11

Ismail Badawi


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)
like image 24
Yarik Avatar answered Nov 13 '22 15:11

Yarik