Django remove bulk-delete

This is a very simple question: Is there a good way to disable the bulk delete call (via queries, of course) for all models in the entire Django project?

The reason for this is the premise that deletion is almost always a bad choice, and random volume-deletion can be harmful.

+4
source share
2 answers

As in the comments on the first post, you must create a subclass for each of these elements:

  • Model manager
  • Class queryset
  • Basemodel

, , . , :

. : .

from django.db import models
from django.db.models.query import QuerySet


class SoftDeletionQuerySet(QuerySet):
    def delete(self):
        # Bulk delete bypasses individual objects' delete methods.
        return super(SoftDeletionQuerySet, self).update(alive=False)

    def hard_delete(self):
        return super(SoftDeletionQuerySet, self).delete()

    def alive(self):
        return self.filter(alive=True)

    def dead(self):
        return self.exclude(alive=True)


class SoftDeletionManager(models.Manager):
    def __init__(self, *args, **kwargs):
        self.alive_only = kwargs.pop('alive_only', True)
        super(SoftDeletionManager, self).__init__(*args, **kwargs)

    def get_queryset(self):
        if self.alive_only:
            return SoftDeletionQuerySet(self.model).filter(alive=True)
        return SoftDeletionQuerySet(self.model)

    def hard_delete(self):
        return self.get_queryset().hard_delete()


class SoftDeletionModel(models.Model):
    alive = models.BooleanField(default=True)

    objects = SoftDeletionManager()
    all_objects = SoftDeletionManager(alive_only=False)

    class Meta:
        abstract = True

    def delete(self):
        self.alive = False
        self.save()

    def hard_delete(self):
        super(SoftDeletionModel, self).delete()

, alive, , , delete().
, , .

+3

, ( ), , :

, , :

  • . MyModel.objects.all().delete(), , .
  • .

, , :

, QuerySet , , - , , .

0

All Articles