多对多。如何正确创建`Follow`对象?

时间:2013-07-08 13:53:46

标签: django

class Follow(models.Model):
    user = models.ForeignKey(User)
    follow = models.ManyToManyField(User, related_name='following')

的观点:

user_to_follow = User.objects.get(id=follow_id)
f = Follow.objects.create(follow = user_to_follow)

如何在我的案例中正确创建Follow对象?

1 个答案:

答案 0 :(得分:0)

对于ManyToMany fields,你会这样做:

user_to_follow = User.objects.get(id=follow_id)
f = Follow.objects.create(user=request.user) #or user=whatever
f.follow.add(user_to_follow)

或者

user_to_follow = User.objects.get(id=follow_id)
f = Follow(user=request.user) #or user=whatever
f.save()
f.follow.add(user_to_follow)

我也会这样做

from django.shortcuts import get_object_or_404
user_to_follow = get_object_or_404(User, id=follow_id)

因为如果数据库中不存在User.objects.get(id=follow_id) 500 userfollow_id会抛出{{1}}。