问题
I'm trying to do a function that allow a user to follow another one. the problem is when I'm adding a new user to the "followings" the user that follow another user is also added in the following list of the followed user. For example if user a follow user b I will have that:
view.py
def follow_test(request):
name = request.POST.get('name', '')
user_followed = Dater.objects.get(username=name)
current_user = Dater.objects.get(id=request.user.id)
print "Current", current_user.followings.all() # display []
print "Followed", user_followed.followings.all() # display []
current_user.followings.add(user_followed)
print "Current", current_user.followings.all() # display <Dater: b>
print "Followed", user_followed.followings.all() # display <Dater: a>
model.py:
followings = models.ManyToManyField('self', blank=True)
I would like the user b only to be add in the followings of a
回答1:
By default, many-to-many relationships on self are symmetrical. If you don't want this, set symmetrical to False:
followings = models.ManyToManyField('self', blank=True, symmetrical=False)
See the docs
回答2:
Just set related_name="followed_by" for the many to many field. That would assign the reverse mapping to followed_by
followings = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followed_by')
来源:https://stackoverflow.com/questions/41540042/many-to-many-field-django-add-the-relationship-both-way