How do I override delete() on a model and have it still work with related deletes

后端 未结 8 1374
一向
一向 2020-12-13 09:24

I\'m having a problem because I\'m deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I

相关标签:
8条回答
  • 2020-12-13 10:16

    It should look like described on the django site:

    class Blog(models.Model):
        name = models.CharField(max_length=100)
        tagline = models.TextField()
        def save(self, *args, **kwargs):
            do_something()
            super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
            do_something_else()
    

    http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods

    you forgot to pass some arguments

    0 讨论(0)
  • 2020-12-13 10:21

    I'm doing the same thing and noticed a nugget in the Django docs that you should think about.

    Overriding predefined model methods

    Overriding Delete Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.

    This means your snippet will not always do what you want. Using Signals is a better option for dealing with deletions.

    I went with the following:

    import shutil
    from django.db.models.signals import pre_delete 
    from django.dispatch import receiver
    
    @receiver(pre_delete)
    def delete_repo(sender, instance, **kwargs):
        if sender == Set:
            shutil.rmtree(instance.repo)
    
    0 讨论(0)
提交回复
热议问题