【发布时间】: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