Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optionally use select_related to pull related fields for old #415

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions auditlog/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@
settings.AUDITLOG_INCLUDE_TRACKING_MODELS = getattr(
settings, "AUDITLOG_INCLUDE_TRACKING_MODELS", ()
)

# Do select_related on related fields to eliminate unnecessary queries
settings.AUDITLOG_SELECT_RELATED_FIELDS = getattr(
settings, "AUDITLOG_SELECT_RELATED_FIELDS", False
)
18 changes: 16 additions & 2 deletions auditlog/receivers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import json
from itertools import chain

from django.conf import settings
from django.db.models import ForeignKey, OneToOneField, OneToOneRel

from auditlog.diff import model_instance_diff
from auditlog.models import LogEntry
Expand Down Expand Up @@ -27,13 +31,23 @@ def log_update(sender, instance, **kwargs):
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
"""
if instance.pk is not None:
update_fields = kwargs.get("update_fields", None)
try:
old = sender.objects.get(pk=instance.pk)
if settings.AUDITLOG_SELECT_RELATED_FIELDS:
fk_fields = []
for field in chain(sender._meta.fields, sender._meta.related_objects):
if isinstance(field, (ForeignKey, OneToOneField, OneToOneRel)):
if not update_fields or (
update_fields and field.name in update_fields
):
fk_fields.append(field.name)
old = sender.objects.select_related(*fk_fields).get(pk=instance.pk)
else:
old = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist:
pass
else:
new = instance
update_fields = kwargs.get("update_fields", None)
changes = model_instance_diff(old, new, fields_to_check=update_fields)

# Log an entry only if there are changes
Expand Down