Skip to main content

django-typed-models

example workflow

Intro

django-typed-models provides an extra type of model inheritance for Django. It is similar to single-table inheritance in Ruby on Rails.

The actual type of each object is stored in the database, and when the object is retrieved it is automatically cast to the correct model class.

Licensed under the New BSD License.

Features

  • Models in querysets have the right class automatically
  • All models subclassing a common base are stored in the same table
  • Object types are stored in a 'type' field in the database
  • No extra queries or joins to retrieve multiple types

Usage:

An example says a bunch of words:

# myapp/models.py

from django.db import models
from typedmodels.models import TypedModel


class Animal(TypedModel):
    """
    Abstract model
    """

    name = models.CharField(max_length=255)

    def say_something(self):
        raise NotImplemented

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.name)


class Canine(Animal):
    def say_something(self):
        return "woof"


class Feline(Animal):
    mice_eaten = models.IntegerField(default=0)

    def say_something(self):
        return "meoww"

Later:

>>> from myapp.models import Animal, Canine, Feline
>>> Feline.objects.create(name="kitteh")
>>> Feline.objects.create(name="cheetah")
>>> Canine.objects.create(name="fido")
>>> print Animal.objects.all()
[<Feline: kitteh>, <Feline: cheetah>, <Canine: fido>]

>>> print Canine.objects.all()
[<Canine: fido>]

>>> print Feline.objects.all()
[<Feline: kitteh>, <Feline: cheetah>]

You can actually change the types of objects. Simply run an update query:

Feline.objects.update(type="myapp.bigcat")

If you want to change the type of an object without refreshing it from the database, you can call recast:

kitty.recast(BigCat)
# or kitty.recast('myapp.bigcat')
kitty.save()

Listing subclasses

Occasionally you might need to list the various subclasses of your abstract type.

One current use for this is connecting signals, since currently they don't fire on the base class (see #1)

    for sender in Animal.get_type_classes():
        post_save.connect(on_animal_saved, sender=sender)

Django admin

If you plan to use typed models with Django admin, consider inheriting from typedmodels.admin.TypedModelAdmin. This will hide the type field from subclasses admin by default, and allow to create new instances from the base class admin.

from django.contrib import admin
from typedmodels.admin import TypedModelAdmin
from .models import Animal, Canine, Feline


@admin.register(Animal)
class AnimalAdmin(TypedModelAdmin):
    pass


@admin.register(Canine)
class CanineAdmin(TypedModelAdmin):
    pass


@admin.register(Feline)
class FelineAdmin(TypedModelAdmin):
    pass

Limitations

  • Since all objects are stored in the same table, all fields defined in subclasses are nullable.
  • Fields defined on subclasses can only be defined on one subclass, unless the duplicate fields are exactly identical.
  • While post_init receivers run, instance._meta is the base class's _meta, not the subclass's.

Requirements

  • a non-EOL combination of Django and Python

Metadata

Release files for django-typed-models 0.17.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-typed-models 0.17.0
File Size Uploaded
django_typed_models-0.17.0.tar.gz 21.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-typed-models 0.17.0
File Interpreter ABI Platform
django_typed_models-0.17.0-py3-none-any.whl Python 3 none any Details

Total release size: 37.4 kB

Release files / django_typed_models-0.17.0.tar.gz

Download URL django_typed_models-0.17.0.tar.gz
Size 21.6 kB
Tags Source
SHA-256 checksum
How to use checksums
25fe78ac54af62f63bc88996122ae9bd1534d420e99859fc759e345eaa60d911
BLAKE2b-256 checksum
How to use checksums
5efef91cc308e9ee239a9e104186fc293e3e17f1481383e93ef517706e9281d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.19

Release files / django_typed_models-0.17.0-py3-none-any.whl

Download URL django_typed_models-0.17.0-py3-none-any.whl
Size 15.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1cd392494cb273ea6987dadd5d87bdd0e331de8e82014b80458216b72ca8f4a0
BLAKE2b-256 checksum
How to use checksums
76a04a81e7d05ae93a30342a9a75baa5b7bf42984e3cda5c78de7d7340156591
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.19

Release history Release notifications | RSS feed

This release

0.17.0 This release

2 release files

0.16.2

2 release files

0.16.1

2 release files

0.16.0

2 release files

0.15.2

2 release files

0.15.1

2 release files

0.15.0

2 release files

0.14.0

2 release files

0.13.0

2 release files

0.12.0

2 release files

0.11.1

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

1 release file

0.3.1

1 release file

0.3.0

1 release file

0.2.1

1 release file

0.2.0

1 release file

0.1.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page