Through the on_delete parameter , Django provides various alternatives for what to do with objects that have a foreign key for the object that is being deleted.
I am wondering if there is a way to do something similar, but conditionally. Here is the script. I am using the new user model Django 1.5, and all my users have a ForeignKey for the site. For instance:
class TenantSiteUser(AbstractUser): site = models.ForeignKey(Site, null=True)
If the site is deleted, I would prefer to remove all non-superusers associated with this site (i.e., KASKADE behavior), since their existence is now meaningless. But if this is the superuser, I would prefer to just set the user's site to zero (i.e. SET_NULL) and leave them existing, as it is probably me or someone I work with, and we tend to not want to unintentionally delete ourselves .
Is there something I can override to manually validate and implement this type of on_delete behavior?
EDIT: Here's the code that ended for me based on @Kevin's answer and some research on how existing handlers work:
def NULLIFY_SUPERUSERS_ELSE_CASCADE(collector, field, sub_objs, using): superusers = [] for user in sub_objs: if user.is_superuser: sub_objs = list(sub_objs) sub_objs.remove(user) superusers.append(user) CASCADE(collector, field, sub_objs, using) if len(superusers): collector.add_field_update(field, None, superusers) class TenantSiteUser(AbstractUser): site = models.ForeignKey(Site, null=True, on_delete=NULLIFY_SUPERUSERS_ELSE_CASCADE)
source share