python – django-rest-framework django-polymorphic ModelSerialization

栏目: Python · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/19976202/django-rest-framework-django-polymorphic-modelserialization

我想知道是否有人拥有将Django REST框架与django-polymorphic结合在一起的Pythonic解决方案.

鉴于:

class GalleryItem(PolymorphicModel):
    gallery_item_field = models.CharField()

class Photo(GalleryItem):
    custom_photo_field = models.CharField()

class Video(GalleryItem):
    custom_image_field = models.CharField()

如果我想要在django-rest-framework中的所有GalleryItem的列表,它只会给我GalleryItem(父模型)的字段,因此:id,gallery_item_field和polymorphic_ctype.这不是我想要的.如果它是一个视频,我想要custom_photo_field,如果它是一个Photo实例和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, 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)

对于POST和PUT请求,您可能想要使用to_internal_value def来执行类似于覆盖to_representation定义的类似操作.

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/19976202/django-rest-framework-django-polymorphic-modelserialization


以上所述就是小编给大家介绍的《python – django-rest-framework django-polymorphic ModelSerialization》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

游戏数据分析的艺术

游戏数据分析的艺术

于洋、余敏雄、吴娜、师胜柱 / 机械工业出版社 / 2015-7 / 79.00

《游戏数据分析的艺术》是中国游戏产业的开创性著作,具有里程碑意义,它首次系统讲解了如何对游戏行业的数据进行分析,在行业里竖起了一根标杆。作者是来自TalkingData等国内顶尖的数据分析机构和西山居这样的知名游戏公司的资深数据分析专家, 对游戏数据从不同的业务角度进行了诠释。本书详细剖析了游戏数据分析相关的指标、方法论、内容挖掘、数据挖掘、软件使用、游戏设计、运营策划、渠道推广、收入解读、用户分......一起来看看 《游戏数据分析的艺术》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具