Clear nullable foreign keys on delete

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def clear_nullable_related(self):
    """
    Recursively clears any nullable foreign key fields on related objects.
    This simulates ON DELETE SET NULL behavior manually.
    """
    for related in self._meta.get_all_related_objects():
        accessor = related.get_accessor_name()
        related_set = getattr(self, accessor)

        if related.field.null:
            related_set.clear()
        else:
            for related_object in related_set.all():
                related_object.clear_nullable_related()

Comments

jdunck (on December 11, 2008):

psagers, I'm not on 1.0 yet, but reading the code in model.delete() and delete_objects(), it sure looks to me like Django goes out of its way to avoid deleting nullable foreign keys on model_instance.delete.

Is this an actual problem you're seeing? Are you doing Model.delete or QuerySet.delete?

In any case, it sounds like it might be a bug. Did you file a ticket?

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.