【问题标题】:DJANGO ListView returns HTTPResponse, but I need a jsonDJANGO ListView 返回 HTTPResponse,但我需要一个 json
【发布时间】:2021-10-18 10:41:20
【问题描述】:

我在 Django 中遇到基于类的视图的问题。我需要创建 JSON 响应,而不是渲染到模板。

class AllItem(ListView):
    model = MyModel
    context_object_name = 'items'
    template_name = 'mymodel/index.html'

我也有一个序列化器类

class SpendingConfigSerializer(serializers.ModelSerialier):
    class Meta:
        model = SpendingConfig
        fields = ('record_date', 'amount', 'name')

有人知道如何连接它们吗?

谢谢 Z.

【问题讨论】:

  • 您应该使用ListAPIView。您指定template_name 也很奇怪。

标签: json django serialization


【解决方案1】:

您可以使用ListAPIView 并将您的SpendingConfigSerializer 指定为序列化程序:

from rest_framework import generics

class UserList(generics.ListCreateAPIView):
    queryset = SpendingConfig.objects.all()
    serializer_class = SpendingConfigSerializer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-29
    • 2018-10-11
    • 2020-11-02
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多