【问题标题】:Manipulate serialization result for a many=true serialization为 many=true 序列化操作序列化结果
【发布时间】:2020-11-24 19:10:54
【问题描述】:

我想操作一个many=True序列化的序列化结果:

class CustomContentElementSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomContentElement
        fields = [
            'type',
            'html'
        ]

result = CustomContentElementSerializer(
    CustomContentElement.objects.all(),
    many=True
)

我不想操纵单个对象序列化结果,而是操纵完整列表。使用覆盖函数to_representation,我只能操作返回列表的单个元素。

我认为这很复杂,因为 ModelSerializer 类在构造函数中设置了它的基类(第 117 行:https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py

有人知道如何在many=True 序列化的末尾操纵结果吗?

解决方案(谢谢@MSR974):

class CustomContentElementListSerializer(serializers.ListSerializer):
    
    def to_representation(self, data):
        data = super().to_representation(data)
        return self.manipulate_list_representation(data)

    def manipulate_list_representation(self, data):
        data.reverse()
        return data

class CustomContentElementSerializer(serializers.ModelSerializer):
    image = FilerImageFieldSerializer()

    class Meta:
        list_serializer_class = CustomContentElementListSerializer
        model = CustomContentElement
        fields = [
            'type',
            'col_id',               
        ]  

https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior的文档中

【问题讨论】:

  • 你说的“manipulate”是什么意思?你想做什么?
  • 我需要将其转换为字典,因为我需要一个特殊的结构。这对这个问题并不重要。如果在序列化程序中不可能,我会在视图中进行。但我认为在序列化程序中这样做会更干净。
  • 到一个字典?这没有任何意义,因为您要处理多个具有相同键的模型对象。
  • 我需要添加一些元信息。我可以在视图中添加它,但是因为每次序列化此类数据时都需要它,所以我认为将它放在序列化程序中会更干净:{“info_a”:“Whatever”,“items”:[item_a, item_b, ...] }

标签: django django-rest-framework


【解决方案1】:

是的,正如预期的那样,“很多”意味着序列化重复 x 次,其中 x 是它必须处理的对象数

您可能应该使用自定义 ListSerializer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2022-01-07
    • 2018-12-18
    • 1970-01-01
    • 2016-03-15
    • 2016-01-12
    相关资源
    最近更新 更多