1
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对象?

4

1 回答 1

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)

因为,如果数据库中不存在withUser.objects.get(id=follow_id)会抛出一个。500userfollow_id

于 2013-07-08T13:55:36.800 回答