Python DoesNotExist at/home/Friend匹配查询不存在

Python DoesNotExist at/home/Friend匹配查询不存在,python,django,Python,Django,朋友匹配查询不存在 此错误是因为您的查询为空.get()将返回错误。使用.filter()代替合适的条件 看这张文件 当.get()直接返回一个对象时,filter()返回一个queryset,因此您必须检查queryset是否为空,然后使用queryset.first()或queryset[0] 另一种解决方案是将.get()包装在try/except块中: from home.models import Post,Friend from django.contrib.auth.models

朋友匹配查询不存在

此错误是因为您的查询为空<如果查询为空或包含多个结果,code>.get()将返回错误。使用
.filter()
代替合适的条件

看这张文件

.get()
直接返回一个对象时,
filter()
返回一个queryset,因此您必须检查queryset是否为空,然后使用
queryset.first()
queryset[0]

另一种解决方案是将
.get()
包装在try/except块中:

from home.models import Post,Friend
from django.contrib.auth.models import User


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()

显示完整的错误回溯此错误让您感到困惑的是什么?当前用户没有朋友。AttributeError位于/home/“QuerySet”对象在使用筛选器()时没有出现属性“users”
try:
    friend=Friend.objects.get(current_user=request.user)
except:
    # No Friend was found for this current_user
    # Do something