148👍
✅
You should use aggregates.
from django.db.models import Count
User.objects.annotate(page_count=Count('page')).filter(page_count__gte=2).count()
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)
- [Django]-Django's self.client.login(…) does not work in unit tests
- [Django]-Select between two dates with Django
- [Django]-Why there are two process when i run python manage.py runserver
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"))
- [Django]-Django – how to visualize signals and save overrides?
- [Django]-Login Page by using django forms
- [Django]-Django. A good tutorial for Class Based Views
Source:stackexchange.com