Search code examples
djangomanytomanyfieldsql-limit

django ORM return top 10 match in manytomany relationship


My models.py has a manytomany relationship between User and Tag

class Tag(models.Model):
    name = models.CharField(unique=True, max_length=32)

class User(AbstractBaseUser, PermissionsMixin):
    tags = models.ManyToManyField(Tag, blank=True)    

How can I get top 10 tags ordered by the number of users with the tag? Something like

Tag.objects.order_by('user_set__count')[10]

This command doesn't work and django complains that

django.core.exceptions.FieldError: Cannot resolve keyword 'myuser_set' into field. Choices are: id, myuser, name

This is puzzling because t1.user_set.count() works where t1 is a Tag instance.

Also, is there a better way to get the top 10 without order all data?


Solution

  • below query return list of tags ordered by user count :

    tags = Tag.objects.all().annotate(num_user = Count('user')).order_by('-num_user')
    

    if you want 10 top, use this query:

    tags = Tag.objects.all().annotate(num_user = Count('user')).order_by('-num_user')[:10]