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:
ModelAbstract 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 (
ForeignKeytoContentType) –Polymorphic ctype
The model field that stores the
ContentTypereference to the actual class.
- delete(using=None, keep_parents=False)¶
Behaves the same as Django’s default
delete(), but with support for upcasting whenkeep_parentsis True. When keeping parents (upcasting the row) thepolymorphic_ctypefields 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
PolymorphicTypeInvalidexception.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_ctypevalue 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:
ForeignKeytoContentTypePolymorphic ctype
The model field that stores the
ContentTypereference to the actual class.