我在另一个序列化器中使用嵌套序列化器,并且我有两个模型Object
和ObjectMedia
,请参见以下代码:
class ObjectMediaSerializer(serializers.ModelSerializer):
media_address = serializers.SerializerMethodField()
class Meta:
model = ObjectMedia
fields = ["media_address", "type"]
class ObjectAddEditSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(read_only=True)
object_medias = ObjectMediaSerializer(many=True, required=True)
class Meta:
model = Program
fields = [
"slug",
"object_medias",
]
我想在两个字段中添加对象媒体(由其类型分隔),如下所示,但我不知道如何实现:
{
"slug":"my_slug",
"object_media_type1": [
{
"media_address ": "somewhere",
"type":TYPE1
}
],
"object_media_type2": [
{
"media_address ": "somewhere",
"type":TYPE2
},
{
"media_address ": "somewhere\else",
"type":TYPE2
}]
}
1条答案
按热度按时间gab6jxml1#
您可以使用
SerializerMethodField
:请注意,它们是只读的。此处为官方文档。