From 236bdd067aa28f8140c0e0c9b8f3e7210ffa9b5f Mon Sep 17 00:00:00 2001
From: Christoph Berg <myon@debian.org>
Date: Fri, 16 Oct 2026 16:01:21 +0200
Subject: [PATCH v14 06/12] Use select_related for the badge holder and people
 lookups

peoplelist() loaded Contributors with prefetch_related('user') and
badge_view() loaded Badgeholders with prefetch_related('user__contributor').
Both traverse a forward foreign key (Contributor.user, Badgeholder.user)
and, in badge_view(), a reverse one-to-one (user.contributor), so a join
fetches them in the same query: one query instead of two for the people
list, and one instead of three for a badge page.

The reverse foreign key Prefetch('badge') in profile() stays a prefetch,
as a reverse relation cannot be fetched with select_related().
---
 pgweb/contributors/views.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/pgweb/contributors/views.py b/pgweb/contributors/views.py
index 16c82b1e..3dc04a55 100644
--- a/pgweb/contributors/views.py
+++ b/pgweb/contributors/views.py
@@ -21,7 +21,7 @@ def peoplelist(request):
     # clamp lists to protect against unplanned floods. If we ever get close to
     # the limits, we need to make a plan on how to proceed, but we can't know
     # before we gain some practical experience
-    people = Contributor.objects.prefetch_related('user')[:2000]
+    people = Contributor.objects.select_related('user')[:2000]
     badges = Badge.objects.with_has_image().filter(approved=True)[:200]
     return render_pgweb(request, 'community', 'contributors/people.html', {
         'people': people,
@@ -33,7 +33,7 @@ def badge_view(request, slug):
     badge = get_object_or_404(Badge.objects.with_has_image(), slug=slug, approved=True)
     # badge holders are users, but we want to show only users with a contributor object here
     holders = Badgeholder.objects.filter(badge=badge, user__contributor__isnull=False). \
-        prefetch_related('user__contributor'). \
+        select_related('user', 'user__contributor'). \
         order_by('user__contributor__lastname', 'user__contributor__firstname')
     return render_pgweb(request, 'community', 'contributors/badge.html', {
         'badge': badge,
-- 
2.53.0

