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

fix #1806: N+1 query issue on dashboard index page #1813

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
4 changes: 3 additions & 1 deletion dashboard/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ def setUp(self):
def test_index(self):
for MC in Metric.__subclasses__():
for metric in MC.objects.filter(show_on_dashboard=True):
metric.data.create(measurement=44)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding extra data to ensure the query will retrieve the latest datum for each metric.

metric.data.create(measurement=42)

request = self.factory.get(reverse("dashboard-index", host="dashboard"))
response = index(request)
with self.assertNumQueries(7):
response = index(request)
self.assertContains(response, "Development dashboard")
self.assertEqual(response.content.count(b'<div class="metric'), 13)
self.assertEqual(response.content.count(b"42"), 13)
Expand Down
28 changes: 22 additions & 6 deletions dashboard/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import datetime
import operator

from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.forms.models import model_to_dict
from django.http.response import Http404, JsonResponse
from django.shortcuts import render
from django.utils.translation import gettext as _

from .models import Metric
from .models import Datum, Metric
from .utils import generation_key


Expand All @@ -19,12 +19,28 @@ def index(request):
if data is None:
metrics = []
for MC in Metric.__subclasses__():
metrics.extend(MC.objects.filter(show_on_dashboard=True))
metrics = sorted(metrics, key=operator.attrgetter("display_position"))
metrics.extend(
MC.objects.filter(show_on_dashboard=True).select_related("category")
)

content_types = ContentType.objects.get_for_models(*metrics)
datum_queryset = Datum.objects.none()
for metric, content_type in content_types.items():
datum_queryset = datum_queryset.union(
Datum.objects.filter(
content_type_id=content_type.id, object_id=metric.id
).order_by("-timestamp")[0:1]
)

latest_datums = {
(datum.object_id, datum.content_type_id): datum for datum in datum_queryset
}

data = []
for metric in metrics:
data.append({"metric": metric, "latest": metric.data.latest()})
for metric, content_type in content_types.items():
if latest := latest_datums.get((metric.id, content_type.id)):
data.append({"metric": metric, "latest": latest})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a better way to write this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've been trying to find an alternate approach (got pretty close with a Datum.objects.values('content_type', 'object_id').annotate(Max('timestamp')) but unfortunately that can only get the latest timestamp for each metric, not the associated measurement).

Your original approach using UNION seems quite good (and it's quite clever).

I've made a suggestion for a slight rewrite that is a bit shorter and also closer to the original view implementation (it does so by pushing some logic onto the Datum manager). If you like it I can push a commit onto this branch.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good! It's very interesting how you've moved most of the logic to DatumQuerySet!

The only concern is that latest = latest_by_metric.get((metric.content_type.pk, metric.pk)) could return None. Will the frontend be able to handle rendering of None?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, the current behavior for a metric with no data is for the view to crash, so it can't be worse than that 😁
(good call though, I'll test it out)

data = sorted(data, key=lambda elem: elem["metric"].display_position)
cache.set(key, data, 60 * 60, version=generation)

return render(request, "dashboard/index.html", {"data": data})
Expand Down
Loading