Return response in django rest-framework

I am writing an application in 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) 

I want to return an error status code if the request returns None. But the problem, if I try to install Response, causes an error:

 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 

Otherwise, if the query result is not None, it works. How can I set the status code in the Django rest-framework.

+4
source share
2 answers

Can you try this

 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 

I think it will work ...

+1
source

The method is expected to return a QuerySet object, not a Response object, my bet is that you should throw an Exception , either an APIException , or an Http404 .

In any case, your processing seems strange, I think you just need to return a QuerySet, and the infrastructure will be processed if the result is empty or not. The method should look like this:

 def get_queryset(self): return tags.objects.filter(tag='burger') 
+5
source

All Articles