Home > Net >  How to count the number of specific objects in a Django model?
How to count the number of specific objects in a Django model?

Time:07-09

I have a Django model called User and would like to count how many items are within the following object.

class User(AbstractUser):
    following = models.ManyToManyField("self", related_name="followers")

I have tried counting them using this line followers_num = User.following.count(), but I receive this error 'ManyToManyDescriptor' object has no attribute 'count'.

I have also tried followers_num = User.objects.all().count(), but that returns the number of users.

Does anyone know how to do this?

CodePudding user response:

You can count the total number of following relations with:

User.following.through.objects.count()  # total number of following relations

If you want to add an extra attribute to the User objects with the number of followings per User, you can use:

from django.db.models import Count

User.objects.annotate(
    num_following=Count('following')  # number of following per (!) user
)

Note: A ManyToManyField [Django-doc] to itself is by default symmetrical, so that means that if A is a following of B, then B is automatically a following of A, you likely do not want that. You can turn this off with symmetrical=False [Django-doc].

CodePudding user response:

I will suppose you want to get the user followers so you will First find the User

user = User.objects.get(pk=1)
user.following.all() # this will get you the followers of this user 

user count to get their count, comment if that doesn't match what you need

  • Related