爲了完成,我添加了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