Django Polymorphic

4.11.2 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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)

view raw JSON →