简体   繁体   中英

Django - how can i return a json response error?

I created a simple API endpoint using Django Rest Framework and i created a very basic logic where if the user doesn't provide any filter, the API needs to return a custom error, something like {'error': 'no parameter provided'} . The problem with my code is that i keep getting this error: object of type 'JsonResponse' has no len() .

Here is my code:

class WS_View(viewsets.ModelViewSet):
    pagination_class = StandardResultsSetPagination
    http_method_names = ['get']
    serializer_class = WS_Serializer

    def get_queryset(self):

        valid_filters = {
            ...
        }

        filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()}

        #If there are filters, execute the query
        if len(filters) > 0:
            queryset = WS.objects.filter(**filters)
            return queryset
        #If there isn't any filter, return an error
        else:
            return JsonResponse({"error": "no parameter required"})

Now i know i'm getting this error because i'm supposed to return a Queryset, and JsonResponse is not a Queryset of course, but i don't know how to actually solve this. Any advice is appreciated!

As you already realized, get_queryset expects (as its name suggests) a queryset. So the solution is to raise an exception here:

from rest_framework.exceptions import NotFound

class WS_View(viewsets.ModelViewSet):
   #...
    def get_queryset(self):
        #...
        if len(filters) > 0:
            queryset = WS.objects.filter(**filters)
        else:
            raise NotFound("no parameter required")

I used NotFound, but you can find a list of Exceptions in DRF documentation that might suit you better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM