django - 提取 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=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}
解决方案
我解决它的方法是覆盖视图集中的 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
推荐阅读
- javascript - 如果我为数据库中的对象分配动态创建的值,是否可以使用 fetch 命令访问该值?
- c# - Dot Net Core 未在 Ubuntu 中打开私钥
- python - 将两列长度相等的列合并为一列
- regex - 不遵循 Scrapy CrawlSpider 规则?
- flutter - 使用 MaterialPageRoute 刷新背面
- php - 多对多关系 - 将数据从多个表移动到单个表
- android - Button.setOnClickListener() 在我的代码中不起作用
- cmake - 错误的 CMake 安装目录
- javascript - ajax 错误返回中的特定 SQLState 处理
- mysql - 如何:按值及其在表中的新位置对用户进行排序