django-rest-framework + django-polymorphic ModelSerialization [英] django-rest-framework + django-polymorphic ModelSerialization
问题描述
我想知道是否有人拥有将Django REST框架与django-polymorphic结合在一起的Pythonic解决方案。
给定:
$ $ $ $ $ $ $ $ $
class照片(GalleryItem):
custom_photo_field = models.CharField()
class视频(GalleryItem):
custom_image_field = models.CharField()
如果我想要在django-rest-framework中的所有GalleryItem的列表,它只会给我GalleryItem(父模型)的字段,因此:id,gallery_item_field和polymorphic_ctype。这不是我想要的。我想要custom_photo_field如果它是一个照片实例和custom_image_field如果它是一个视频。
到目前为止,我只测试了GET请求,这样做:
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Photo
class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Video
class GalleryItemModuleSerializer(serializers.ModelSerializer):
class Meta:
model = models.GalleryItem
def to_representation(self,因为GalleryItem是多态的
如果isinstance(obj,models.Photo):
返回PhotoSerializer(obj,context = self.context).to_representation(obj)
elif isinstance(obj,models.Video):
return VideoSerializer(obj,context = sel f.context).to_representation(obj)
return super(GalleryItemModuleSerializer,self).to_representation(obj)
对于POST和PUT请求,您可能想要使用to_internal_value def来替代to_representation定义进行类似的操作。
I was wondering if anyone had a Pythonic solution of combining Django REST framework with django-polymorphic.
Given:
class GalleryItem(PolymorphicModel):
gallery_item_field = models.CharField()
class Photo(GalleryItem):
custom_photo_field = models.CharField()
class Video(GalleryItem):
custom_image_field = models.CharField()
If I want a list of all GalleryItems in django-rest-framework it would only give me the fields of GalleryItem (the parent model), hence: id, gallery_item_field, and polymorphic_ctype. That's not what I want. I want the custom_photo_field if it's a Photo instance and custom_image_field if it's a Video.
So far I only tested this for GET request, and this works:
class PhotoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Photo
class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = models.Video
class GalleryItemModuleSerializer(serializers.ModelSerializer):
class Meta:
model = models.GalleryItem
def to_representation(self, obj):
"""
Because GalleryItem is Polymorphic
"""
if isinstance(obj, models.Photo):
return PhotoSerializer(obj, context=self.context).to_representation(obj)
elif isinstance(obj, models.Video):
return VideoSerializer(obj, context=self.context).to_representation(obj)
return super(GalleryItemModuleSerializer, self).to_representation(obj)
For POST and PUT requests you might want to do something similiar as overriding the to_representation definition with the to_internal_value def.
这篇关于django-rest-framework + django-polymorphic ModelSerialization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!