Query ContentTypes instead of distinct LogEntry

SELECT DISTINCT app_label, model FROM log_entry is a very expensive
request for longer logs, while we can always get the list of all
tracked models straight from the registry.

This new approach has two downsides:
1. It only provides filters for currently tracked models.
2. It can list such filter options that don't have any log entries.
This commit is contained in:
Alieh Rymašeŭski 2019-05-17 12:38:39 +03:00
parent ee6bb33bc9
commit cfbc588cc1
2 changed files with 20 additions and 3 deletions

View file

@ -1,4 +1,9 @@
from django.contrib.admin import SimpleListFilter
from django.contrib.contenttypes.models import ContentType
from django.db.models import Value
from django.db.models.functions import Concat
from auditlog.registry import auditlog
class ResourceTypeFilter(SimpleListFilter):
@ -6,9 +11,17 @@ class ResourceTypeFilter(SimpleListFilter):
parameter_name = 'resource_type'
def lookups(self, request, model_admin):
qs = model_admin.get_queryset(request)
types = qs.values_list('content_type_id', 'content_type__model')
return list(types.order_by('content_type__model').distinct())
tracked_model_names = [
'{}.{}'.format(m._meta.app_label, m._meta.model_name)
for m in auditlog.list()
]
model_name_concat = Concat('app_label', Value('.'), 'model')
content_types = ContentType.objects.annotate(
model_name=model_name_concat,
).filter(
model_name__in=tracked_model_names,
)
return content_types.order_by('model_name').values_list('id', 'model_name')
def queryset(self, request, queryset):
if self.value() is None:

View file

@ -114,6 +114,10 @@ class AuditlogModelRegistry(object):
'mapping_fields': self._registry[model]['mapping_fields'],
}
def list(self):
"""Get a list of all registered models."""
return list(self._registry.keys())
class AuditLogModelRegistry(AuditlogModelRegistry):
def __init__(self, *args, **kwargs):