views.py
def get(self, request):
form = HomeForm()
posts = Post.objects.all().order_by('-created')
users = User.objects.exclude(id=request.user.id,
friend = Friend.objects.get(current_user=request.user),
friends = friend.users.all())
args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends}
return render(request, self.template_name, args)
models.py
class Post(models.Model):
post = models.CharField(max_length=500)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Friend(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='owner', null=True)
@classmethod
def make_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create( current_user=current_user )
friend.users.add(new_friend)
答案 0 :(得分:0)
如果朋友匹配的查询不存在,则必须使用try except
。
您有关于该文档的文档:Try Except
你第一次写:
try :
...
except :
#when you get doesn't exist