Skip to content

Instantly share code, notes, and snippets.

Created Apr 20, 2018
What would you like to do?
Delete Stats stacker
class DeleteStats(object):
Object that allows stacking the results of .delete()
You can initialise it with or without data:
> stats = DeleteStats()
> stats = DeleteStats(some_queryset.delete())
You can stack delete results from different types of querysets/model instances:
> stats = DeleteStats()
> stats.extend(SomeModel.objects.filter(...).delete())
> stats.extend(SomeOtherModel.objects.filter(...).delete())
> stats.extend(some_object.delete())
It can be unpacked like a tuple, so that it behaves the way that Django's API does:
> total_deleted, removed_by_model = stats
And it print out everything using a logger:
> logger = logging.getLogger(__name__)
> stats.log(logger)
def __init__(self, delete_output=None):
super(DeleteStats, self).__init__()
self.total_removed = 0
self.removed_by_model = defaultdict(int)
if delete_output:
def extend(self, delete_output):
total_removed, removed_by_model = delete_output
self.total_removed += total_removed
for _model, _count in removed_by_model.iteritems():
self.removed_by_model[_model] += _count
return self
def __getitem__(self, index):
# Pretend to be a tuple to match how the django API returns deletes
if index == 0:
return self.total_removed
elif index == 1:
return self.removed_by_model
raise IndexError()
def log(self, _logger):"Deleted {} objects in total".format(self.total_removed))
for model_name, count in self.removed_by_model.iteritems():"- {model_name} deleted: {count}".format(
model_name=model_name, count=count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment