django-rest-framework + django-polymorphic ModelSerialization

django-rest-framework + django-polymorphic ModelSerialization,第1张

django-rest-framework + django-polymorphic ModelSerialization

到目前为止,我仅对GET请求进行了测试,并且可以正常工作:

class PhotoSerializer(serializers.ModelSerializer):    class meta:        model = models.Photoclass VideoSerializer(serializers.ModelSerializer):    class meta:        model = models.Videoclass 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://outofmemory.cn/zaji/5645909.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存