Dear Django Users,
I have been running into a problem with the app I am developing and I
haven't been able to find a good solution. Suppose I have the following
model:
class MyModel(models.Model):
a = models.CharField(max_length=255, null=True, blank=True)
b = models.ForeignKey('MyOtherModel', null=True, blank=True,
on_delete=models.SET_NULL)
# some more model fields
The task I am trying to accomplish is the following: If an instance of
"MyOtherModel" is deleted, a and b of the related MyModel-instance
should be set to NULL in the database, but the instance of MyModel with
the other fields should remain. The model above only sets b to NULL but
not a.
Any ideas?
Regards,
Jannfrom django.db import models
class SetNull(object):
"""Deletion handler that behaves like `SET_NULL` but also
takes a list of extra fields to NULLify."""
def __init__(self, *fields):
self.fields = fields
def __call__(self, collector, field, sub_objs, using):
# Set the field this is attached to NULL
models.SET_NULL(collector, field, sub_objs, using)
for field in self.fields:
models.SET_NULL(collector, field, sub_objs, using)
class MyModel(models.Model):
a = models.CharField(max_length=255, null=True, blank=True)
b = models.ForeignKey(
'MyOtherModel', null=True, blank=True, on_delete=SetNull(a)
)