简体   繁体   中英

How to return a json in get_queryset()?

I want to return a error message in JSON format from a get_queryset() if error occurs. Does anyone knows hot to do it?

    def get_queryset(self):
        try:
            #some code that returns a queryset
        except:
            return Response({"status": "ERROR!"})

But obviously I`m unable to do that. Does anyone knows how to resolve this?

One possible way is to somehow convert the message into queryset and return it. But I don`t know how to do it!

I suppose that if you want to return a Response the get_queryset() method is inside a class-based view. As the name says the method itself can only return a QuerySet , though inside a view you can raise certain exceptions which are turned into a response by Django's built-in exception handling .

You can eg. raise an Http404 and Django will automatically respond with 404 response status.

This behaviour you can customize and eg. return a JsonResponse instead of the normal response.

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