Django - Annotate with count across ManytoMany relationships
I am not able to find the way to annotate a queryset with a count of how many times an element is used in a many-to-many relationship.
class Profile(models.Model):
[...]
# Profile can have multiple roles
roles = models.ManyToManyField('Role', blank=True)
[...]
class Role(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
name = models.CharField(blank=True, max_length=30)
description = models.CharField(blank=True, max_length=300)
[...]
For example I would have 5 roles:
- Role1
- Role2
- Role3
- Role4
- Role5
And 2 profiles with following roles assigned:
- Profile1
- Role 1
- Role 2
- Profile2
- Role 1
- Role 3
- Role 4
I need to have the oposite than @ha-duy:
Profile: name, role_count=2
Profile: name, role_count=3
Any ideas?
Thanks!