Michael van de Waeter Michael van de Waeter - 2 months ago 10
Python Question

django-rest-framework + django-polymorphic ModelSerialization

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.

Answer

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.

Comments