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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With