许多对很多领域的django都是双向关系

时间:2017-01-09 02:11:04

标签: python django database many-to-many

我试图做一个允许用户关注另一个的功能。问题是当我向"以下"添加新用户时跟随另一个用户的用户也会添加到以下用户的以下列表中。例如,如果用户是跟随用户b,我将具有:

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只能添加到

的以下内容中

2 个答案:

答案 0 :(得分:4)

默认情况下,self上的多对多关系是对称的。如果您不想这样做,请将symmetrical设置为False:

followings = models.ManyToManyField('self', blank=True, symmetrical=False)

请参阅the docs

答案 1 :(得分:1)

为多对多字段设置related_name =“followed_by”。这会将反向映射分配给followed_by

followings = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='followed_by')
相关问题