views:

27

answers:

1

In this topic I found a good way to prevent cascade deleting of relating objects, when it's not neccessary.

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

But this method seems to fail when we are using ForeignKey field with "related_name" parameter. As it seems to me, "clear()" method works fine and saves the instance of "deassociated" object. But then, while deleting, django uses another memorized copy of this very object and since it's still associated with object we are trying to delete - whooooosh! ...bye-bye to relatives :)

Database was arcitectured before me, and in somewhat odd way, so I can't escape these "related_names" in reasonable amount of time. Anybody heard about workaround for such a trouble?

+1  A: 

What about re-reading the object again and delete that?

to_delete = self.__class__.objects.get(pk=self.pk)
to_delete.delete()

That way is the deleted object is a new fresh copy. The problem is to do all properly other stuff that the original delete() method has to do, like signal calling, return the correct value, etc...

Mandx
In fact, that method is working for me. I'm using Django 1.2 (checkout of the stable branch). Also, it's documented when deleting an object using actions (right in the admin object list, not the change form), the `delete()` method of the object it's not called, since it's bulk deletion (`QuerySet.delete()`)
Mandx
Thanks Mandx, I'll give it a try. Not sure when, since my line of work went faaaaar beyond this piece of code :)
Wiseman