Django why model foreign key cascade will not trigger delete?
there two basic ways to do something when an instance gets deleted
:
- Overwrite
Model.delete
- Signal
I used to reckon both of them serve the same purpose, just provides different ways of writing, but works exactly.
However, in this occasion, I realise I was wrong:
class Human(models.Model):
name = models.CharField(max_length=20)
class Pet(models.Model):
name = models.CharField(max_length=20)
owner = models.ForeignKey(Human, related_name="pet", on_delete=models.CASCADE)
def delete(self, *args, **kwargs):
print('------- Pet.delete is called')
return super().delete(*args, **kwargs)
h = Human(name='jason')
h.save()
p = Pet(name="dog", owner=h)
p.save()
h.delete()
# nothing is shown
Why Pet.delete
Is not firing at Human.delete
By the foreign cascade? Does I have to apply a signal on this? If so, would it cost more performance?
I am building something very heavy, comment system, filter decent records and delete when the commented target get deleted, the comment model has many null-able foreign key fields, with models.CASCADE
Set, only one of them is assigned with value. But in product delete view, I call product.delete
Then triggers cascade
, but comment.delete
Is not firing.
Currently, the project has delete
Defined on many models, with assumption that it is always triggered when the instance get removed from database
, and it is tremendous work to rewrite it in signal. Is there a way to call delete
When at cascading? (I know it is likely impossible since it is a database field specification)