#Good way to implement nested soft delete

1 messages · Page 1 of 1 (latest)

lime shard
#

As we usually implement soft delete in models, we create column like is_deleted and update it to True when we make a delete option, and we use a manager like following

class BaseManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().filter(is_deleted=False)

This work good when we are working with one model and easy to maintain also, I was experimenting with multiple relations where we have multiple child models for same parent model, for example we can say user models is parent and when user ask to delete the object, we mark object is_deleted=True, and all of user entry in other related models also

Following is something I tried

 def delete(self, using=None, keep_parents=False):
        for related_object in self._meta.related_objects:
            if related_object.on_delete == models.CASCADE:
                if OneToOneField == type(related_object.field):
                    try:
                        child = getattr(self, related_object.get_accessor_name())
                        child.delete()
                    except Exception as e:
                        print(e)
                else:
                    for child in getattr(self, related_object.get_accessor_name()).all():
                        child.delete()
        self.is_deleted = True
        self.save()

The issue with this is if there are too many child records, it can run too many db queries which is not good, I was watching a DjangoCon video which shared a soft delete use case with good library option
https://django-pgtrigger.readthedocs.io/en/4.6.0/module.html#pgtrigger.SoftDelete

I tried it as well but like I was mentioning that I have a base model which has is_deleted column in all tables,

class BaseModel(models.Model):
    is_deleted = models.BooleanField(default=False)

so not sure update the meta class in base model is good idea, I was just testing some relations and it was also giving some integrity error also.

Is there a good way to do soft delete for all child models without running way too many db queries.

#

Good way to implement nested soft delete