polymorphic.models

Seamless Polymorphic Inheritance for Django Models

exception polymorphic.models.PolymorphicTypeInvalid

Bases: RuntimeError

exception polymorphic.models.PolymorphicTypeUndefined

Bases: LookupError

class polymorphic.models.PolymorphicModel

Bases: Model

Abstract base class that provides polymorphic behaviour for any model directly or indirectly derived from it.

PolymorphicModel declares one field for internal use (polymorphic_ctype) and provides a polymorphic manager as the default manager (and as ‘objects’).

Relationship fields:

Parameters:

polymorphic_ctype (ForeignKey to ContentType) –

Polymorphic ctype

The model field that stores the ContentType reference to the actual class.

delete(using=None, keep_parents=False)

Behaves the same as Django’s default delete(), but with support for upcasting when keep_parents is True. When keeping parents (upcasting the row) the polymorphic_ctype fields of the parent rows are updated accordingly in a transaction with the child row deletion.

get_real_instance()

Upcast an object to it’s actual type.

If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the complete object with it’s real class/type and all fields may be retrieved with this method.

If the model of the object’s actual type does not exist (i.e. its ContentType is stale), this method raises a PolymorphicTypeInvalid exception.

Note

Each method call executes one db query (if necessary). Use the get_real_instances() to upcast a complete list in a single efficient query.

get_real_instance_class()

Return the actual model type of the object.

If a non-polymorphic manager (like base_objects) has been used to retrieve objects, then the real class/type of these objects may be determined using this method.

pre_save_polymorphic(using='default')

Make sure the polymorphic_ctype value is correctly set on this model.

This method automatically updates the polymorphic_ctype when: - The object is being saved for the first time - The object is being saved to a different database than it was loaded from

This ensures cross-database saves work correctly without ForeignKeyViolation.

save(*args, **kwargs)

Calls pre_save_polymorphic() and saves the model.

polymorphic_ctype

Type: ForeignKey to ContentType

Polymorphic ctype

The model field that stores the ContentType reference to the actual class.