Django: how to aggregate / annotate over a many-to-many relationship?

瘦欲@ 提交于 2019-12-04 21:29:50

问题


I have a Person model and a Tag model, with a m2m between them.

I need to extract the tag which is connected to the most records within a given Person queryset, together with the count.

Is there an elegant, efficient way to extract this using the Django ORM?

Better yet, is there a way to get the entire tag distribution through some annotation? How can one even pull all of the objects connected to a subset of objects connected via a m2m?

Thanks!


回答1:


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]



回答2:


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')


来源:https://stackoverflow.com/questions/3613080/django-how-to-aggregate-annotate-over-a-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!