Registry / web-framework / django-rest-polymorphic

django-rest-polymorphic

JSON →
library0.1.10pypypi✓ verified 25d ago

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-polymorphic
INSTALL
IMPORT
SIG · DJANGO-REST-POLYMO
D
django-rest-polymorphic
web-frameworkpythonv0.1.10
Install
3.9s avg
Import
862ms
Disk
71MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.1.10 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.906s · 71.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.9s · import 0.818s · 72MB
71MB installed
● package 71MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PolymorphicSerializer
from rest_polymorphic.serializers import PolymorphicSerializer
from polymorphic.contrib.drf.serializers import PolymorphicSerializer
While this was the original import for django-rest-polymorphic, the core functionality (PolymorphicSerializer) has been incorporated into django-polymorphic itself. The recommended import path for new projects or migrations is now `from polymorphic.contrib.drf.serializers import PolymorphicSerializer`.

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`.

from django.db import models from rest_framework import serializers, viewsets from polymorphic.models import PolymorphicModel from rest_polymorphic.serializers import PolymorphicSerializer # 1. Define polymorphic models using django-polymorphic class Project(PolymorphicModel): topic = models.CharField(max_length=30) class ArtProject(Project): artist = models.CharField(max_length=30) class ResearchProject(Project): supervisor = models.CharField(max_length=30) # 2. Define serializers for each concrete model class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('topic', 'resource_type') # 'resource_type' is added automatically by PolymorphicSerializer class ArtProjectSerializer(serializers.ModelSerializer): class Meta: model = ArtProject fields = ('topic', 'artist', 'resource_type') class ResearchProjectSerializer(serializers.ModelSerializer): class Meta: model = ResearchProject fields = ('topic', 'supervisor', 'resource_type') # 3. Create a PolymorphicSerializer to map models to serializers class ProjectPolymorphicSerializer(PolymorphicSerializer): model_serializer_mapping = { Project: ProjectSerializer, ArtProject: ArtProjectSerializer, ResearchProject: ResearchProjectSerializer } # 4. Use the polymorphic serializer in a ViewSet class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectPolymorphicSerializer
Debug
Known issues
breakingThe core `PolymorphicSerializer` functionality has been incorporated directly into `django-polymorphic` (specifically at `polymorphic.contrib.drf.serializers.PolymorphicSerializer`). While `django-rest-polymorphic` still exists, the recommended approach for new projects or migrating existing ones is to switch imports.
fix
Change import statements from `from rest_polymorphic.serializers import PolymorphicSerializer` to `from polymorphic.contrib.drf.serializers import PolymorphicSerializer`.
affects: All versions, as this is a migration path recommendation for users of `django-polymorphic`'s built-in DRF support.
gotchaWhen extending `HyperlinkedModelSerializer` instead of `ModelSerializer`, you need to explicitly define `extra_kwargs` to direct the URL to the appropriate view for your polymorphic serializer. This ensures correct URL generation for specific child types.
fix
Add `extra_kwargs` to your child serializers' `Meta` class, for example: `extra_kwargs = {'url': {'view_name': 'drf:project-detail', 'lookup_field': 'pk'}}`.
affects: All versions
gotchaBy default, the polymorphic type is identified by a field named `resource_type`. If you need to use a different field name in your API requests/responses, you must override the `resource_type_field_name` attribute.
fix
Set `resource_type_field_name = 'your_custom_type_field'` on your `PolymorphicSerializer` subclass.
affects: All versions
gotchaUsing `django-polymorphic` (and consequently `django-rest-polymorphic`) for model inheritance can have performance implications. Each query to a base polymorphic model will result in `INNER JOIN` operations to fetch fields from subclassed models.
fix
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.
affects: All versions (inherent to `django-polymorphic` design)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'rest_polymorphic.serializers'
The core functionality of `django-rest-polymorphic` has been integrated into the `django-polymorphic` library itself, meaning the original `rest_polymorphic` module path is no longer the primary way to import its serializers.
fix
Change your import paths from `rest_polymorphic.serializers` to `polymorphic.contrib.drf.serializers`.
AttributeError: 'Manager' isn't accessible via WorkflowNotification instances
This error occurs when you attempt to access a Django model manager (like `objects`) from a model instance rather than from the model class itself, a common anti-pattern that can manifest with polymorphic models when trying to perform queryset operations from an instance method.
fix
Access the manager via the model class (e.g., `Notification.objects.filter(...)`) instead of a model instance (`self.objects.filter(...)`).
django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'my_app_artproject' with primary key '1' has an invalid foreign key: my_app_artproject.project_ptr_id contains a value '1' that does not have a corresponding value in my_app_project.id.
This `IntegrityError` typically arises when using Django's `dumpdata` and `loaddata` management commands with `django-polymorphic` models, as the default dumpdata often fails to correctly serialize the `ContentType` and parent model `_ptr` (pointer) foreign key relationships, leading to missing references during loading or incorrect cascade deletions.
fix
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.
Upgrade
Version history
0.1.10latest on PyPI · released Jul 17, 2022
Audit
Dependencies
django-polymorphicrequiredRequired for defining polymorphic models that django-rest-polymorphic serializes.
djangorestframeworkrequiredIt's an extension for Django REST Framework.
Agent activity
11 hits · last 30 days
node
10
Resources
django-rest-polymorphic — pip install django-rest-polymorphic · libregistry