从同一个模型在序列化器中创建两个字段
make two fields in serializer from a same model
我在另一个序列化器中使用嵌套序列化器,我有两个模型 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
}]
}
感谢阅读
您可以使用 SerializerMethodField
:
class ObjectAddEditSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(read_only=True)
object_media_type1 = serializers.SerializerMethodField()
object_media_type2 = serializers.SerializerMethodField()
def get_object_media_type1(self, instance):
return ObjectMediaSerializer(instance.object_medias.filter(type="type1"), many=True).data
def get_object_media_type2(self, instance):
return ObjectMediaSerializer(instance.object_medias.filter(type="type2"), many=True).data
class Meta:
model = Program
fields = [
"slug",
"object_media_type1",
"object_media_type2",
]
请注意他们是 read-only。官方文档 here.
我在另一个序列化器中使用嵌套序列化器,我有两个模型 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
}]
}
感谢阅读
您可以使用 SerializerMethodField
:
class ObjectAddEditSerializer(serializers.ModelSerializer):
slug = serializers.SlugField(read_only=True)
object_media_type1 = serializers.SerializerMethodField()
object_media_type2 = serializers.SerializerMethodField()
def get_object_media_type1(self, instance):
return ObjectMediaSerializer(instance.object_medias.filter(type="type1"), many=True).data
def get_object_media_type2(self, instance):
return ObjectMediaSerializer(instance.object_medias.filter(type="type2"), many=True).data
class Meta:
model = Program
fields = [
"slug",
"object_media_type1",
"object_media_type2",
]
请注意他们是 read-only。官方文档 here.