为了完成,我正在添加to_internal_value()
实现,因为我在最近的项目中需要它。
如何确定类型
有可能区分不同的“类”很方便;为此,我将 type 属性添加到基本多态模型中:
class GalleryItem(PolymorphicModel):
gallery_item_field = models.CharField()
@property
def type(self):
return self.__class__.__name__
这允许将其type
称为“字段”和“只读字段”。
type
将包含 python 类名。
向序列化程序添加类型
您可以将其添加type
到“字段”和“只读字段”中(如果您想在所有子模型中使用它们,则需要在所有序列化程序中指定类型字段)
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Photo
fields = ( ..., 'type', )
read_only_fields = ( ..., 'type', )
class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Video
fields = ( ..., 'type', )
read_only_fields = ( ..., 'type', )
class GalleryItemModuleSerializer(serializers.ModelSerializer):
class Meta:
model = models.GalleryItem
fields = ( ..., 'type', )
read_only_fields = ( ..., 'type', )
def to_representation(self, obj):
pass # see the other comment
def to_internal_value(self, data):
"""
Because GalleryItem is Polymorphic
"""
if data.get('type') == "Photo":
self.Meta.model = models.Photo
return PhotoSerializer(context=self.context).to_internal_value(data)
elif data.get('type') == "Video":
self.Meta.model = models.Video
return VideoSerializer(context=self.context).to_internal_value(data)
self.Meta.model = models.GalleryItem
return super(GalleryItemModuleSerializer, self).to_internal_value(data)