为了完成,我添加了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)
我找不到了'to_native'方法的任何文件。它什么时候被叫? –
http://www.django-rest-framework.org/topics/3.0-announcement/#changes-to-the-custom-field-api –
我猜测POST和PUT可能会稍微困难一些(尽管仍然可行),因为您需要确定用户想要提交的内容,在验证之前(如果某个字段丢失,可能无法确定)。 恕我直言,它使用单独的端点写入请求更清洁。 – WhyNotHugo