在Django Rest框架中序列化字符串而不做更改?

2024-06-25 05:31:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是Python的json.dumps文件()将数组转换为字符串,然后将其存储在Django模型中。我正在尝试如何让Django的REST框架忽略这个字段,并按原样发送它,而不需要再次序列化它。在

例如,如果模型如下所示(两个字段都是CharFields):

name = "E:\"

path_with_ids= "[{"name": "E:\", "id": 525}]"

我希望REST框架在序列化时忽略“path_with_ids”,以便JSON输出如下所示:

{ "name": "E:\", "path_with_ids": [ {"name": "E:\", "id": 525} ] }

不是这样的:

{ "name": "E:\", "path_with_ids": "[{\"name\": \"E:\\\", \"id\": 525}]" }

我尝试创建另一个序列化程序类,该类将“原样”获取的输入吐出,但没有成功:

序列化程序.py:

class PathWithIds(serializers.CharField):

    def to_representation(self, value):

        return value.path_with_ids

class FolderSerializer(serializers.ModelSerializer):

field_to_ignore = PathWithIds(source='path_with_ids')

  class Meta:
      model = Folder
      fields = ['id', 'field_to_ignore']

请帮忙!在


Tags: topathdjangoname模型程序框架rest
1条回答
网友
1楼 · 发布于 2024-06-25 05:31:41

最后,我在使用REST框架再次序列化数组之前,使用了一种既浪费又恶心的方法来反序列化数组:

序列化程序.py:

import json
class PathWithIds(serializers.CharField):

    def to_representation(self, value):

        x = json.loads(value)
        return x

class FolderSerializer(serializers.ModelSerializer):

    array_output = PathWithIds(source='field_to_ignore')

      class Meta:
          model = Folder
          fields = ['id', 'array_output']

rest API中的输出:

{ "name": "E:\", "array_output": [ { "name": "E:\", "id": 525 } ] }

相关问题 更多 >