Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Django model with ForeignKeys which does not cascade deletes to its children?

One of my models which has ForeignKey's is actually a MySQL view on other tables. The problem I'm running into is that when I delete data from these tables, Django, as described in the "deleting objects" documentation...

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

...tries to remove rows from my view, which of course it can't, and so throws the error:

mysql_exceptions.OperationalError '>=(1395, "Can not delete from join view 'my_db.my_mysql_view'"'

Is there any way to specify a ForeignKey constraint on a model which will provide me with all the Django wizardry, but will not cascade deletes onto it? Or, is there a way to ask MySQL to ignore the commands to delete a row from my view instead of raising an error?


2 Answers

Django 1.3a1 and up support this via ForeignKey's on_delete argument.

The following example sets the field NULL upon deletion of the foreign key. See the documentation for more options.

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
like image 159
2 revs, 2 users 82%zourtney Avatar answered Sep 15 '25 05:09

2 revs, 2 users 82%zourtney


Harold's answer pointed me in the right direction. This is a sketch on the way I implemented it (on a french legacy database, hence the slightly odd naming convention):

class Factures(models.Model):
    idFacture = models.IntegerField(primary_key=True)
    idLettrage = models.ForeignKey('Lettrage', db_column='idLettrage', null=True, blank=True)

class Paiements(models.Model):
    idPaiement = models.IntegerField(primary_key=True)
    idLettrage = models.ForeignKey('Lettrage', db_column='idLettrage', null=True, blank=True)

class Lettrage(models.Model):
    idLettrage = models.IntegerField(primary_key=True)

    def delete(self):
        """Dettaches factures and paiements from current lettre before deleting"""
        self.factures_set.clear()
        self.paiements_set.clear()
        super(Lettrage, self).delete()
like image 45
Rod Daunoravicius Avatar answered Sep 15 '25 04:09

Rod Daunoravicius