I am trying to return custom json with get_queryset but always get 404 error in response.

class TestViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Test.objects.all()
    serializer_class = TestSerializer

    def get_queryset(self):
        if self.request.method == "GET":
            content = {'user_count': '2'}
            return HttpResponse(json.dumps(content), content_type='application/json')

If I delete everything starting from def I'll got correct response with standard json data. What I am doing wrong?

推荐答案

如果您不需要ModelViewSet而只需要GET请求上的自定义JSON

你也可以使用APIView,它不需要模型

class MyOwnView(APIView):
    def get(self, request):
        return Response({'some': 'data'})

and

urlpatterns = [
    url(r'^my-own-view/$', MyOwnView.as_view()),
]

使用ModelViewSet

You've put the custom JSON into get_queryset, that's wrong. If you want to use a ModelViewSet, this by itself should be enough:

class TestViewSet(viewsets.ModelViewSet):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

ModelViewSet附带.list().retrieve().create().update().destroy()的默认实现.这些选项可供您根据需要覆盖(自定义)

Returning custom JSON from .retrieve() and/or .list() in ModelViewSet

E.g. to override .retrieve() to return custom view when retrieving a single object. We can have a look at the default implementation which looks like this:

def retrieve(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = self.get_serializer(instance)
    return Response(serializer.data)

以返回自定义JSON为例:

class TestViewSet(viewsets.ModelViewSet):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

    def retrieve(self, request, *args, **kwargs):
        return Response({'something': 'my custom JSON'})

    def list(self, request, *args, **kwargs):
        return Response({'something': 'my custom JSON'})

Json相关问答推荐

Vega-Lite时钟(使用Vega-Lite中的计时器)

如何在PowerShell中扩展JSON中的嵌套数组

如何使用Aeson解码带有Unicode字符的JSON文件?

如何在改装Android中将ResponseBody转换为JSONObject

当列为空时从 SQL 获取 JSON

如何编写 jolt 规范以将不同的对象转换为数组

父键中的 Perl JSON 数组

嵌套 JSON 到 CSV(多级)

Nifi - 忽略(或删除)JSON 的第一个数字

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

如何在linux中用jq过滤json数组?

使用 c# 通用地展平 Json

如何为名称/值 struct 创建 JSON 模式?

使用 GSON 解析嵌套的 JSON 数据

在 Postgres 中向 JSON 对象添加元素

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

使用 C# 调用 json

如何从 jQuery ajax 调用将复杂对象传递给 ASP.NET WebApi GET?

如何在 React js 中解析本地 JSON 文件?

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象