Skip to content

Commit

Permalink
Optionally optimize table truncation supplying a low level query stat…
Browse files Browse the repository at this point in the history
…ement in settings.
  • Loading branch information
morlandi committed Nov 12, 2017
1 parent 8a5fdc5 commit 5bf687d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
include LICENSE
include README.rst
recursive-include easyaudit/static *
recursive-include easyaudit/templates *
16 changes: 14 additions & 2 deletions easyaudit/admin_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from django.contrib import messages
from django.conf.urls import url
from django.utils.safestring import mark_safe
from . import settings


class EasyAuditModelAdmin(admin.ModelAdmin):
Expand Down Expand Up @@ -51,6 +52,16 @@ def purge_objects(self, request):
This action first displays a confirmation page;
next, it deletes all objects and redirects back to the change list.
"""

def truncate_table(model):
if settings.TRUNCATE_TABLE_SQL_STATEMENT:
from django.db import connection
sql = settings.TRUNCATE_TABLE_SQL_STATEMENT.format(db_table=model._meta.db_table)
cursor = connection.cursor()
cursor.execute(sql)
else:
model.objects.all().delete()

modeladmin = self
opts = modeladmin.model._meta

Expand All @@ -65,8 +76,9 @@ def purge_objects(self, request):
if request.method == 'POST':
if 'btn-confirm' in request.POST:
try:
modeladmin.model.objects.all().delete()
modeladmin.message_user(request, _("Successfully removed all objects"), messages.SUCCESS);
n = modeladmin.model.objects.count()
truncate_table(modeladmin.model)
modeladmin.message_user(request, _("Successfully removed %d rows" % n), messages.SUCCESS);
except Exception as e:
modeladmin.message_user(request, _(u'ERROR') + ': %r' % e, messages.ERROR)
else:
Expand Down
12 changes: 11 additions & 1 deletion easyaudit/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,14 @@ def get_model_list(class_list):
for idx, callback in enumerate(CRUD_DIFFERENCE_CALLBACKS):
if not callable(callback): # keep as is if it is callable
CRUD_DIFFERENCE_CALLBACKS[idx] = getattr(import_module('.'.join(callback.split('.')[:-1])),
callback.split('.')[-1], None)
callback.split('.')[-1], None)

# Purge table optimization:
# If TRUNCATE_TABLE_SQL_STATEMENT is not empty, we use it as custom sql statement
# to speed up table truncation bypassing ORM, i.e.:
# DJANGO_EASY_AUDIT_TRUNCATE_TABLE_SQL_STATEMENT = "TRUNCATE TABLE `{db_table}`" # for Postgresql
# Else we use Django Orm as follows:
# model.objects.all().delete()
# which is however much costly when many rows are involved
TRUNCATE_TABLE_SQL_STATEMENT = getattr(settings, 'DJANGO_EASY_AUDIT_TRUNCATE_TABLE_SQL_STATEMENT', '')

0 comments on commit 5bf687d

Please sign in to comment.