From 1d54c2f98ee49501268e45b71302f91f4c313a30 Mon Sep 17 00:00:00 2001 From: gagandeep trivedi Date: Tue, 20 Jul 2021 19:23:09 +0530 Subject: [PATCH] fix(audit_log): Prefetch Fk relations to avoid n+1 (#197) * fix(audit_log): Prefetch Fk relations to avoid n+1 Closes: https://github.com/Flagsmith/flagsmith/issues/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 --- api/audit/views.py | 4 +++- api/tests/integration/audit/test_audit_logs.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 api/tests/integration/audit/test_audit_logs.py diff --git a/api/audit/views.py b/api/audit/views.py index 6c112d2944a8..ce2d8c7f2073 100644 --- a/api/audit/views.py +++ b/api/audit/views.py @@ -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: diff --git a/api/tests/integration/audit/test_audit_logs.py b/api/tests/integration/audit/test_audit_logs.py new file mode 100644 index 000000000000..5e6ce7d78fc7 --- /dev/null +++ b/api/tests/integration/audit/test_audit_logs.py @@ -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