Skip to content

Commit 1d54c2f

Browse files
authored
fix(audit_log): Prefetch Fk relations to avoid n+1 (#197)
* 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
1 parent 8f0578f commit 1d54c2f

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

api/audit/views.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ def get_queryset(self):
4444
self.request.query_params.get("environment")
4545
)
4646
q = q & (Q(environment__id=environment_id) | Q(environment=None))
47-
return AuditLog.objects.filter(q)
47+
return AuditLog.objects.filter(q).select_related(
48+
"project", "environment", "author"
49+
)
4850

4951
def _get_value_as_int(self, value):
5052
try:
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from django.urls import reverse
2+
from rest_framework import status
3+
4+
5+
def test_audit_logs_only_makes_two_queries(
6+
admin_client, project, environment, django_assert_num_queries
7+
):
8+
url = reverse("api-v1:audit-list")
9+
10+
with django_assert_num_queries(2):
11+
res = admin_client.get(url, {"project": project})
12+
13+
assert res.status_code == status.HTTP_200_OK
14+
assert res.json()["count"] == 1

0 commit comments

Comments
 (0)