django-rest-polymorphic is a Python library that provides polymorphic serializers for Django REST Framework. It enables you to easily define serializers for models that utilize inheritance through the django-polymorphic library. The current version is 0.1.10, and while its core functionality has been integrated into django-polymorphic, the standalone package is still available on PyPI.
pip install django-rest-polymorphicVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up polymorphic models using `django-polymorphic`, define individual `ModelSerializer`s for each concrete type, and then create a `PolymorphicSerializer` to handle the mapping. Finally, it shows how to integrate this into a Django REST Framework `ViewSet` to expose a polymorphic API endpoint. You would then include this ViewSet in your Django project's `urls.py`.
Change import statements from `from rest_polymorphic.serializers import PolymorphicSerializer` to `from polymorphic.contrib.drf.serializers import PolymorphicSerializer`.
Add `extra_kwargs` to your child serializers' `Meta` class, for example: `extra_kwargs = {'url': {'view_name': 'drf:project-detail', 'lookup_field': 'pk'}}`.Set `resource_type_field_name = 'your_custom_type_field'` on your `PolymorphicSerializer` subclass.
Be mindful of performance for very deep inheritance hierarchies or extremely large datasets. Consider alternative inheritance strategies if performance becomes a critical bottleneck. Ensure appropriate database indexing.
Change your import paths from `rest_polymorphic.serializers` to `polymorphic.contrib.drf.serializers`.
Access the manager via the model class (e.g., `Notification.objects.filter(...)`) instead of a model instance (`self.objects.filter(...)`).
When dumping data, use the `--natural-foreign` flag with `manage.py dumpdata` (e.g., `python manage.py dumpdata --natural-foreign --indent=4 my_app > data.json`) to ensure foreign key relationships, including polymorphic ones, are serialized by value rather than primary key.