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!
This would give you the most frequent tag:
I faced a similar problem before. In my case the m2m relationship was defined between
Unit
andWeapon
models. I used the following query to find out the number of weapons used by eachUnit
and sort them in descending order of number of weapons.I would adjust the query for your requirement thus: