在django rest-framework中返回响应

5 python django django-templates django-views django-rest-framework

我在django rest-framework中编写了一个应用程序:My views.py:

class tagList(generics.ListCreateAPIView,APIView):

    model = tags
    serializer_class = getAllTagsDetailSerializer
    def get_queryset(self):
        print "q1"
        print self.request.QUERY_PARAMS.get('tag', None)
        print self.request.user
        print "q1"
        if tags.objects.filter(tag='burger')!= None:
             return tags.objects.filter(tag='burger')
        else:
            content = {'please move along': 'nothing to see here'}
            return Response(content, status=status.HTTP_404_NOT_FOUND)
Run Code Online (Sandbox Code Playgroud)

如果查询返回None,我想返回错误状态代码.但问题是,如果我尝试设置响应它会抛出错误:

Exception Type: TypeError
Exception Value:    
object of type 'Response' has no len()
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/paginator.py in _get_count, line 53
Run Code Online (Sandbox Code Playgroud)

否则,如果查询结果为"无",则表示正常.如何在Django rest-framework上设置状态代码.

Cla*_*ini 5

该方法应该返回一个QuerySet,而不是一个Response对象,我的赌注是你应该抛出Exception一个APIException或一个Http404.

无论如何,你的处理看起来很奇怪,我认为你应该只返回QuerySet,如果结果为空,框架将处理.该方法应如下所示:

def get_queryset(self):
    return tags.objects.filter(tag='burger')
Run Code Online (Sandbox Code Playgroud)


vai*_*ain 2

你能试试这个吗

model = tags # Model name
serializer_class = getAllTagsDetailSerializer # Call serializer

def get_queryset(self):
    key = self.request.QUERY_PARAMS.get('appKey', None)
    getTagName = self.request.QUERY_PARAMS.get('tagName')
    keyData = app.objects.filter(appKey=key).exists()    
    try:
        if keyData == True:
            return tags.objects.filter(tag=getTagName)
        else:
            raise exceptions.PermissionDenied
    except app.DoesNotExist:
        pass
Run Code Online (Sandbox Code Playgroud)

我认为它会起作用......