在django中添加好友错误

时间:2017-06-08 13:31:44

标签: django python-3.x django-views

我可以从一个用户登录,当我尝试使用其他用户帐户登录时,我收到以下错误

Friend matching query does not exist.

下面是我的views.py。我在第7行收到错误

class HomeView(TemplateView):
    template_name = 'home/home.html'
    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)

2 个答案:

答案 0 :(得分:0)

如果

QuerySet.get()在给定条件的数据库中找不到一个且只有一个条目,则会引发异常。

你可以这样做:

try:
    friend = Friend.objects.get(current_user=request.user)
except Friend.DoesNotExist:
    # handle the error here, maybe add the friend? 
except Friend. MultipleObjectsReturned:
    # multiple friends

或:

current_user_friends = Friend.objects.filter(current_user=request.user)
if not current_user_friends.exists():
    # handle the error here, maybe add the friend?
else:
    friend = current_user_friends[0]
    # at this point, request.user can have more than one friend

鉴于您正在寻找request.user的朋友,您可以尝试:

friends = request.user.friends.all()

假设您的Friend模型类似于:

class Friend(models.Model):
    user = models.ForeignKey(User, ..., related_name='friends')
    ...

希望这有帮助!

答案 1 :(得分:0)

还可以确保您在添加好朋友模型后进行迁移和迁移