首页 > 解决方案 > 提取 id 字段作为关键 django rest 框架序列化程序

问题描述

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

如果我要创建一个模型序列化程序,它将序列化为:

[
   {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 在评论中所说,覆盖 to_representation 有效。但现在它序列化为:

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

这几乎是同样的问题。我不能立即在前端访问它们,因为它是一个数组。我希望它成为所有博客的对象,而不是像上面那样的数组。我认为它变成一个数组的原因是,当我创建序列化程序时,我是这样使用的many=Trueblog_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}

标签: djangodjango-modelsdjango-rest-frameworkdjango-serializer

解决方案


我解决它的方法是覆盖视图集中的 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

推荐阅读