I'm trying to implement a network where users can follow each other in django like so:
> class User(AbstractUser):
> followings = models.ManyToManyField('self', related_name='followers', symmetrical=False)
So the followings
field is going to contain all the users a user is following, and I would also like to be able to access all of the user's followers, thus the related_name
.
My question is, if I have a user's username, how can I make a query to retrieve that user object, with the annotation of its number of followings and number of followers? Here's what I've tried:
data = User.objects.annotate(number_of_followers=Count('followers'), number_of_followings=Count('followings')).get(username=user)
It seems alright to me, but somehow it's showing values that doesn't match the real numbers as in the actual database, as I've checked using the django admin app.
question from:
https://stackoverflow.com/questions/65682175/how-to-get-count-of-objects-in-a-manytomanyfield-with-self-its-own-model-in 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…