Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:

class WidgetFile(models.Model):      widget = models.ForeignKey(Widget) 

Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.

like image 598
orokusaki Avatar asked Oct 08 '09 00:10

orokusaki


People also ask

What happens when you delete model database?

Delete a model to remove the model and all of its data from Master Data Services. When you complete this procedure, all objects and all data from all versions of the model will be permanently deleted.

What is soft delete in Django?

This is a set of small classes to make soft deletion of objects. Use the abstract model SoftDeleteModel for adding two new fields: is_deleted - is a boolean field, shows weather of a deletion state of object.


1 Answers

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) 
like image 194
ElementalVoid Avatar answered Sep 19 '22 21:09

ElementalVoid