Skip to content

Commit

Permalink
fix(audit_log): Prefetch Fk relations to avoid n+1 (#197)
Browse files Browse the repository at this point in the history
* fix(audit_log): Prefetch Fk relations to avoid n+1

Closes: #174

* test(audit_logs): Add test to check the number of query executed

The test will make sure that we are not executing more than 2 queries
in the API(one for the result and the other one for pagination)

* !fixup: inspect the response to check the count
  • Loading branch information
gagantrivedi authored Jul 20, 2021
1 parent 8f0578f commit 1d54c2f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion api/audit/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ def get_queryset(self):
self.request.query_params.get("environment")
)
q = q & (Q(environment__id=environment_id) | Q(environment=None))
return AuditLog.objects.filter(q)
return AuditLog.objects.filter(q).select_related(
"project", "environment", "author"
)

def _get_value_as_int(self, value):
try:
Expand Down
14 changes: 14 additions & 0 deletions api/tests/integration/audit/test_audit_logs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from django.urls import reverse
from rest_framework import status


def test_audit_logs_only_makes_two_queries(
admin_client, project, environment, django_assert_num_queries
):
url = reverse("api-v1:audit-list")

with django_assert_num_queries(2):
res = admin_client.get(url, {"project": project})

assert res.status_code == status.HTTP_200_OK
assert res.json()["count"] == 1

0 comments on commit 1d54c2f

Please sign in to comment.