9π
β
This would give you the most frequent tag:
from django.db.models import Count
Tag.objects.filter(person__yourcriterahere=whatever [, morecriteria]).annotate(cnt=Count('person')).order_by('-cnt')[0]
π€GJ.
5π
I need to extract the tag which is connected to the most records within a given Person queryset, together with the count.
I faced a similar problem before. In my case the m2m relationship was defined between Unit
and Weapon
models. I used the following query to find out the number of weapons used by each Unit
and sort them in descending order of number of weapons.
from django.db.models import Count
q = Unit.objects.all().annotate(count = Count('weapons')).order_by('-count')
I would adjust the query for your requirement thus:
q = User.objects.all().annotate(count = Count('tag')).order_by('-count')
π€Manoj Govindan
- Django: prefetch related objects of a GenericForeignKey
- Django request Post json
- How to solve the circular import error in django?
- Daterange on a django-filter
Source:stackexchange.com