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
对象?
答案 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
user
,follow_id
会抛出{{1}}。