polymorphic.deletion

Classes and utilities for handling deletions in polymorphic models.

class polymorphic.deletion.PolymorphicGuard

Bases: object

Wrap an django.db.models.ForeignKey.on_delete callable (CASCADE/PROTECT/SET_NULL/SET(…)/custom), but serialize as the underlying callable.

Parameters:

action – The django.db.models.ForeignKey.on_delete callable to wrap.

__call__(collector, field, sub_objs, using)

This guard wraps an on_delete action to ensure that any polymorphic queryset passed to it is converted to a non-polymorphic queryset before proceeding. This prevents issues with cascading deletes on polymorphic models.

This guard should be automatically applied to reverse relations such that

class MyModel(PolymorphicModel):
    related = models.ForeignKey(
        OtherModel,
        on_delete=models.CASCADE # <- equal to PolymorphicGuard(models.CASCADE)
    )
__init__(action)
classmethod __new__(*args, **kwargs)
class polymorphic.deletion.PolymorphicGuardSerializer

Bases: BaseSerializer

A serializer for PolymorphicGuard that serializes the underlying action.

There is no need to serialize the PolymorphicGuard itself, as it is just a wrapper that ensures that polymorphic querysets are converted to non-polymorphic but no polymorphic managers are present in migrations. This also ensures that new migrations will not be generated.

serialize()

Serialize the underlying action of the PolymorphicGuard.