简体   繁体   English

Django CBV 返回 JsonResponse?

[英]Django CBVs to return a JsonResponse?

I have been using Django for some time, but running into some issues with trying something new.我一直在使用 Django 一段时间,但在尝试新事物时遇到了一些问题。

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我已经使用基于 Class 的视图构建了带有 Django-Rest-Framework 的 API,并且我还使用基于 Function 的视图构建了 API,返回了JsonResponse

Now what I am tasked to do is use CBV's to return a JsonResponse without using DRF.现在我的任务是在不使用 DRF 的情况下使用 CBV 返回JsonResponse 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.使用模型pk我一直遇到这个简单请求的问题。 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我收到TypeError 'BusinessDetail' object is not iterable如果我做了一些小的更改并覆盖get_object我会得到同样的错误,或者我什至会得到一个'BusinessDetail' object is not callable

Does anybody have any tips with using CBVs to return Json, without using DRF?在不使用 DRF 的情况下,是否有人对使用 CBV 返回 Json 有任何提示?

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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