2013-07-08 94 views
1
class Follow(models.Model): 
    user = models.ForeignKey(User) 
    follow = models.ManyToManyField(User, related_name='following') 

觀點:ManyToMany。如何正確創建`Follow`對象?

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

如何正確地創建在我的案件Follow對象?

回答

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是不存在 在數據庫中。