简体   繁体   中英

Django CBVs to return a JsonResponse?

I have been using Django for some time, but running into some issues with trying something new.

I have built API's with Django-Rest-Framework using Class Based Views, and I have also built API's using Function based views returning a JsonResponse

Now what I am tasked to do is use CBV's to return a JsonResponse without using DRF. I am trying to produce a simple get request

class BusinessDetailView(DetailView):
    model = BusinessDetail

    def get_queryset(self):
        business = BusinessDetail.objects.get(id=self.kwargs.get('pk'))
        return JsonResponse({'business': list(business)})

Using the models pk I keep running into issues with this simple request. I am getting a TypeError 'BusinessDetail' object is not iterable and if I make some small changes and override get_object I'll get the same error, or I'll even get a 'BusinessDetail' object is not callable

Does anybody have any tips with using CBVs to return Json, without using DRF?

Thank you all in advance!

i would try something like this:

class BusinessDetailView(DetailView):
    model = BusinessDetail

    def get_queryset(self):
        business = BusinessDetail.objects.get(id=self.kwargs.get('pk'))
        return business

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        data = serializers.serialize("json", queryset)
        return JsonResponse(data, status=200, safe=False) 

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