本文介绍了多对多字段django双向添加关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行一项允许用户关注另一个功能的功能.问题是,当我将新用户添加到关注对象"中时,关注另一个用户的用户也会添加到关注用户的以下列表中.例如,如果用户a跟随用户b,我将拥有:
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)
我希望仅将用户b添加到a的以下内容中
I would like the user b only to be add in the followings of a
推荐答案
默认情况下,自我上的多对多关系是对称的.如果您不想这样做,请将symmetrical
设置为False:
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)
请参见文档
这篇关于多对多字段django双向添加关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!