Django cascade delete on reverse foreign keys

前端 未结 2 1912
一个人的身影
一个人的身影 2021-02-13 12:55

Django shows how to set or override cascade deletes with foreign keys in their documents.

model = models.ForeignKey(MyModel, null = True, on_delete = models.SET         


        
2条回答
  •  时光说笑
    2021-02-13 13:20

    I don't think the feature you are looking at is an ORM or database concept. You just want to execute a callback when something is deleted.

    So use the post_delete signal and add you callback handler there

    from django.db.models.signals import post_delete
    from django.dispatch import receiver
    from myapp.models import MyModel
    
    @receiver(post_delete, sender=MyModel)
    def my_post_delete_callback(sender, **kwargs):
        #Sender is the model which when deleted should trigger this action
        #Do stuff like delete other things you want to delete
        #The object just deleted can be accessed as kwargs[instance]
    

提交回复
热议问题