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:
For POST and PUT requests you might want to do something similiar as overriding the to_representation definition with the to_internal_value def.
Here's a general and reusable solution. It's for a generic
Serializer
but it wouldn't be difficult to modify it to useModelSerializer
. It also doesn't handle serializing the parent class (in my case I use the parent class more as an interface).And to use it:
For sake of completion, I'm adding
to_internal_value()
implementation, since I needed this in my recent project.How to determine the type
Its handy to have possibility to distinguish between different "classes"; So I've added the type property into the base polymorphic model for this purpose:
This allows to call the
type
as "field" and "read only field".type
will contain python class name.Adding type to Serializer
You can add the
type
into "fields" and "read only fields" (you need to specify type field in all the Serializers though if you want to use them in all Child models)