Django 1.0 is apparently hard-coded for cascading deletes. I find that I often have nullable foreign keys on models whose records must not be deleted along with those they refer to. I override Model.delete() in an intermediate base class and execute this method to clear out all nullable foreign keys before allowing a delete to proceed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from django.db import models
class Model(models.Model):
"""
Intermediate model base class.
"""
class Meta:
abstract = True
def delete(self, *args, **kwargs):
self.clear_nullable_related()
super(Model, self).delete(*args, **kwargs)
def clear_nullable_related(self):
"""
Recursively clears any nullable foreign key fields on related objects.
Django is hard-wired for cascading deletes, which is very dangerous for
us. 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()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
@jdunck this is still a problem. Even in Django 1.2.1
#
I've modified clear_nullable_related() because I was getting exceptions in some cases. Here is my modified code:
#
Django 1.3 has support for "ON DELETE": ForeignKey.on_delete
#
Please login first before commenting.