2

当我执行以下代码配置文件按预期添加到 user_profile.following 时,但 user_profile 也添加到 profile.following (这是不需要的)为什么会发生这种情况,我感觉它与 ForeignKey 是 ' self',但我不知道如何解决它......这是视图:

def follow(request, profile_id):
    user = request.user
    profile = get_object_or_404(Profile, pk=profile_id)
    user_profile = get_object_or_404(Profile, pk=user.id)

    user_profile.following.add(profile)


    return HttpResponseRedirect(reverse('twitter:profile', args=(profile.id,)))

和模型:

class Profile(models.Model):
    user = models.ForeignKey(User)
    bio = models.TextField()
    image = models.ImageField(upload_to='images/%Y/%m/%d/')
    following = models.ManyToManyField('self')
4

1 回答 1

1

好吧,经过更多的窥探,我终于找到了答案,以防其他人想知道解决方案:在模型中,以下应该是

following = models.ManyToManyField('self', symmetrical=False)
于 2013-10-07T04:05:57.130 回答