Search code examples
djangodjango-rest-frameworkdjango-serializerdjango-polymorphic

How to find serializer for a django model?


I am working on a project in which I am using django-polymorphic for retrieving polymorphic result sets. I have some models which inherit from a parent model. For example, Model B inherits from Model A and Model C also inherits from Model A. Model B and Model C have their own serializers and when I query all records for model A, I get a mixed resultset containing instance of Model B and C.

How can I dynamically select serializer based on the instance?

Thanks


Solution

  • Check out Django REST Polymorphic. It is an integration of Django REST Framework with Django Polymorphic. It does exactly what you want.

    All you need to do is to create serializers for each submodel of your parent model, create PolymorphicSerializer that will contain mapping of each model to corresponding serializer and use that PolymorphicSerializer whenever you want.