提取ID字段作为django rest框架序列化键

问题描述

说我有一个Blog模型,其中包含以下字段: id content title

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

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

但是我希望它序列化为此:

{
   '1': {content: "content1",'2': {content: "content2",}

这样,我可以在给定元素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}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)