Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a 404 when drf returns empty queryset using ListAPIView

class listapiview(ListAPIView):

    queryset = testobj.objects.all()
    serializer_class = testobjSerializer
    def get_queryset(self):
        queryset = testobj.objects.all()
        build_id = self.request.query_params.get('id', None)
        if id is not None:
            queryset = queryset.filter(id=id)
        return queryset

I just rewrote some views from APIView to ListAPIView and it broke some of my unittests because an empty queryset still returns a 200. I would like to figure out the best way to return a 404 (or whatever the appropriate error code would be in this) using my example.

I tried adding:

if queryset:
    return queryset
else:
    return Response(status=status.HTTP_404_NOT_FOUND)

But received a paginator error:

TypeError: object of type 'Response' has no len()
like image 548
david Avatar asked Apr 09 '18 17:04

david


1 Answers

raise exception instead of returning Response

django rest framework has multiple predefined exceptions such as NotFound exception, in their exception module. You can add it by importing it from the exception

from rest_framework.exceptions import NotFound 

and modify your get_queryset logic by the following code

if queryset:
    return queryset
else:
    raise NotFound()
like image 200
Aneesh R S Avatar answered Oct 23 '22 11:10

Aneesh R S