Skip to main content
 首页 » 编程设计

python之Django 使用 add 添加对象为 'self' 的 ManyToManyField

2025年05月04日27think

当我执行以下代码时,配置文件按预期添加到 user_profile.following,但 user_profile 也添加到 profile.following(这是不需要的)为什么会发生这种情况,我感觉它与ForeignKey 是“self”,但我不确定如何修复它...这是 View :

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') 

请您参考如下方法:

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

following = models.ManyToManyField('self', symmetrical=False)