Many to many field django add the relationship both way

佐手、 提交于 2019-12-02 02:09:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!