Foreign Key Deletion Problem

30 views
Skip to first unread message

Jann Haber

unread,
Nov 25, 2014, 12:19:48 PM11/25/14
to django...@googlegroups.com
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,

Jann

Simon Charette

unread,
Nov 25, 2014, 4:07:57 PM11/25/14
to django...@googlegroups.com
Hi Jann,

I think you'll need to write a custom deletion handler for this.

The following should work:

from 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)
   
)

Simon

Jann Haber

unread,
Nov 26, 2014, 10:02:41 AM11/26/14
to django...@googlegroups.com
Hi Simon,

thank you very much for your help. I wasn't aware of the possibility of callable class instances. This solved my problem entirely.

Regards,

Jann
Reply all
Reply to author
Forward
0 new messages