<p>为了完成,我添加了<code>to_internal_value()</code>实现,因为我在最近的项目中需要这个。</p>
<p><strong>如何确定类型</p>
<p>有可能区分不同的“类”是很方便的;因此我将type属性添加到基本多态模型中,目的是:</p>
<pre><code>class GalleryItem(PolymorphicModel):
gallery_item_field = models.CharField()
@property
def type(self):
return self.__class__.__name__
</code></pre>
<p>这允许将<code>type</code>称为“字段”和“只读字段”。</p>
<p><code>type</code>将包含python类名。</p>
<p><strong>向序列化程序添加类型</strong></p>
<p>您可以将<code>type</code>添加到“字段”和“只读字段”中
(如果要在所有子模型中使用类型字段,则需要在所有序列化程序中指定类型字段)</p>
<pre><code>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)
</code></pre>