【问题标题】:Extract id field as key django rest framework serializer提取 id 字段作为关键 django rest 框架序列化程序
【发布时间】:2020-12-28 10:05:27
【问题描述】:

假设我有一个博客模型,其中包含以下字段: idcontenttitle

如果我要创建一个模型序列化器,它会序列化到这个:

[
   {id: 1, content: "content1", title: "title1"},
   {id: 2, content: "content2", title: "title2"},
]

但我希望它序列化为:

{
   '1': {content: "content1", title: "title1"},
   '2': {content: "content2", title: "title2"},
}

这样,我可以在前端更快地访问给定 id 的元素,而不必手动搜索 id。 我该怎么做?

编辑: 正如@ArshDoda 在 cmets 中所说,覆盖 to_representation 有效。但现在它序列化为:

[
   {
      "1": {content: "content1", title: "title1"}
   },
   {
      "2": {content: "content2", title: "title2"}
   },
]

这几乎是同样的问题。我不能立即在前端访问它们,因为它是一个数组。我希望它成为所有博客的对象,而不是像上面那样的数组。我认为它成为一个数组的原因是,当我创建序列化程序时,我使用 many=True 像这样:blog_serializer = BlogSerializer(data, many=True)。我该如何解决?

编辑 2: 这是 to_representation 的代码:

def to_representation(self, instance):
    ret = super().to_representation(instance)
    my_id = ret['id']
    del ret['id']
    return {my_id: ret}

【问题讨论】:

  • 使用序列化器中的to_representation函数自定义输出
  • 您能否详细说明或提供任何资源?
  • 谢谢。我会试试看
  • 为什么要获得第二种方式?对于前端,list 或 map 无关紧要,front 无论如何都会做 for 循环,但是让 key id 更加优雅和正确

标签: django django-models django-rest-framework django-serializer


【解决方案1】:

我解决它的方法是覆盖视图集中的 list() 方法:

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

    def list(self, request, *args, **kwargs):  # Override list method to list the data as a dictionary instead of array
        response = super(BlogViewSet, self).list(request, *args, **kwargs)  # Call the original 'list'
        response_dict = {}
        for item in response.data:
            idKey = item.pop('id')  # Remove id from list to use it as key instead
            response_dict[idKey] = item
        response.data = response_dict  # Customize response data into dictionary with id as keys instead of using array
        return response  # Return response with this custom representation

【讨论】:

    猜你喜欢
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多