Wednesday, November 26, 2014

Re: Foreign Key Deletion Problem

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

On Tuesday, November 25, 2014 10:07:57 PM UTC+1, Simon Charette wrote:
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


Le mardi 25 novembre 2014 12:19:48 UTC-5, Yan a écrit :
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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b584ba3a-e695-4dff-ad59-f5adc651381b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment