2

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?

2 Answers 2

1

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].

Sign up to request clarification or add additional context in comments.

2 Comments

I added symmetrical=False and ran migrations, but I do not think anything happened. When I count how many are following and how many followers a user has, both values change if a new user follows that particular user. Will I have to delete all the existing users?
@econo: no, the number of following/follower relations are always the same. symmetrical=False is about how Django handles adding/removing/... items in such ManyToManyField relations.
0

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

2 Comments

This does not work for exactly the same reason as in the question: because User.following is a ManyToManyDescriptor, not a QuerySet or manager...
I am sorry I am wrong I didn't focus I will edit it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.