I have a User model:
class User(AbstractUser):
followers_num = models.IntegerField(default=0)
followings_num = models.IntegerField(default=0)
followers = models.ManyToManyField('self', null=True, blank=True)
followings = models.ManyToManyField('self', null=True, blank=True)
And there’s a view for adding/removing user objects from followers/followings:
def follow(request, follow, user):
if (request.method == 'PUT'):
following_user = User.objects.get(username=user)
follower_user = User.objects.get(username=request.user.username)
if follow:
# Follow
following_user.followers.add(follower_user)
following_user.followers_num += 1
follower_user.followings.add(following_user)
follower_user.followings_num += 1
else:
# Unfollow
following_user.followers.remove(follower_user)
following_user.followers_num -= 1
follower_user.followings.remove(following_user)
follower_user.followings_num -= 1
following_user.save()
follower_user.save()
return HttpResponse(status=204)
I want it to add follower_user
to the followers of following_user
and add following_user
to the followings of follower_user
. However, instead of doing so, it adds follower_user
not only to the followers of following_user
, but it also adds it to the followings of following_user
. Why does it happen?