Registry / database / django-polymorphic

django-polymorphic

JSON →
library4.11.7pypypi✓ verified 30d ago

Django Polymorphic simplifies the use of inherited models in Django projects by automatically returning subclass instances when querying a base model. It enhances Django's multi-table inheritance to provide a seamless polymorphic experience in the ORM and admin interface. The library is actively maintained by the Jazzband community and is currently at version 4.11.2, with regular updates addressing bugs and adding features like comprehensive type annotations.

pip install django-polymorphic
INSTALL
IMPORT
SIG · DJANGO-POLYMORPHIC
D
django-polymorphic
databasepythonv4.11.7
Install
3.7s avg
Import
—
Disk
66MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v4.11.7 · 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.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 67MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 3.7s · import 0.000s · 67MB
66MB installed
● package 66MB
Code
Verified usage

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

PolymorphicModel
✓ from polymorphic.models import PolymorphicModel
✗ from polymorphic.models import PolymorphicModel

This quickstart demonstrates how to define polymorphic models using `PolymorphicModel` and query them. It sets up a minimal Django environment, defines a base `Project` model and two child models (`ArtProject`, `ResearchProject`), creates instances, and then queries the base model to retrieve all objects as their most specific subclass types. It also shows how to filter by `instance_of()` a specific child type. Remember to add 'polymorphic' and 'django.contrib.contenttypes' to `INSTALLED_APPS`.

import os import django from django.conf import settings from django.db import models # Minimal Django setup for runnable example settings.configure( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'polymorphic', __name__ # For models to be registered ], DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} ) django.setup() from polymorphic.models import PolymorphicModel # Define your polymorphic models class Project(PolymorphicModel): topic = models.CharField(max_length=90) def __str__(self): return f"{self.__class__.__name__}: {self.topic}" class ArtProject(Project): artist = models.CharField(max_length=90) def __str__(self): return f"{self.__class__.__name__}: {self.topic} by {self.artist}" class ResearchProject(Project): supervisor = models.CharField(max_length=90) def __str__(self): return f"{self.__class__.__name__}: {self.topic} supervised by {self.supervisor}" # Create database schema from django.core.management import call_command call_command('makemigrations', __name__, interactive=False) call_command('migrate', interactive=False) # Create objects Project.objects.create(topic="Department Party") ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner") ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter") # Query the base model to get polymorphic results all_projects = Project.objects.all() print("All Projects:") for project in all_projects: print(project) # Filter by subclass type art_projects = Project.objects.instance_of(ArtProject) print("\nArt Projects:") for project in art_projects: print(project)
Debug
Known issues
gotchaQuery performance can degrade with many distinct subclasses. Each unique subclass in a queryset requires an additional `INNER JOIN` query to fetch its specific fields, leading to `1 + N` queries (where N is the number of distinct subclasses) for a single `all()` call. While better than `N` queries, it's a consideration for very complex hierarchies.
fix
Be mindful of complex inheritance hierarchies. For large querysets with many distinct subclasses, consider optimizing queries if performance bottlenecks occur. Use `iterator(chunk_size=...)` to balance memory vs. DB round trips.
affects: All versions
breakingThe `drf-polymorphic` package was merged directly into `django-polymorphic` starting with version 4.10.0. This means import paths for `PolymorphicSerializer` and related components have changed.
fix
Update your import paths from `rest_polymorphic.serializers` to `polymorphic.contrib.rest_framework.serializers`.
affects: >=4.10.0
gotchaMethods like `values()` and `values_list()` do not return polymorphic results. They will return fields only from the base model, or specific fields if explicitly requested, but will not perform downcasting to subclasses.
fix
If polymorphic behavior is needed, avoid `values()` and `values_list()` and instead fetch full model instances. If you specifically need non-polymorphic behavior or a fixed set of fields, use `Model.base_objects.values(...)` which is guaranteed not to change.
affects: All versions
gotchaWhen using `dumpdata` with polymorphic models, you must include the `--natural-primary` and `--natural-foreign` flags. Polymorphic models rely on Django's `ContentType` framework, and these flags ensure correct serialization and deserialization across different database instances.
fix
Always use `python manage.py dumpdata --natural-primary --natural-foreign ...` for polymorphic models.
affects: All versions
deprecatedThe keyword argument `polymorphic=False` for disabling polymorphic behavior in queries is no longer supported.
fix
Use the `.non_polymorphic()` queryset method instead, e.g., `ModelA.objects.non_polymorphic().all()`.
affects: Versions >=4.0.0 (exact version where removed is not explicitly stated in latest docs, but `.non_polymorphic()` is the replacement for recent versions)
gotchaIn admin integration, when defining a `PolymorphicChildModelAdmin` that might be extended by further derived classes, use `base_form` and `base_fieldsets` attributes instead of the standard `form` and `fieldsets`. This ensures that additional fields from further child models are automatically added correctly.
fix
Replace `form = ...` with `base_form = ...` and `fieldsets = ...` with `base_fieldsets = ...` in `PolymorphicChildModelAdmin` definitions.
affects: All versions
Upgrade
Version history
4.11.7latest on PyPI · released Aug 1, 2026
Audit
Dependencies
DjangorequiredCore framework dependency for model inheritance and ORM integration.
Agent activity
12 hits · last 30 days
node
10
Resources
django-polymorphic — pip install django-polymorphic · libregistry