django many to many queryset

Viewed 44

i have two models :

1-----

class Account(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=150)
    phone = models.CharField(max_length=50)
    picture = models.ImageField(blank=True, null=True , upload_to='profile' )
    profession = models.ManyToManyField(Profession)

2-----

class Profession(models.Model):
    profession = models.CharField(max_length=50)

i want to display all the profession that i have and in the same time i want to display the number of accounts that they have this profession

like this pic enter image description here

1 Answers

You can annotate per profession name like this:

Profession.objects.values('profession').annotate(num_accounts=Count('account'))

Which will give you an output like:

<ProfessionQuerySet [{'profession': 'SomeProfessionA', 'num_accounts': 22}, {'profession': 'SomeProfessionB', 'num_accounts': 20}, ...>
Related