perf: one grouped query for latest per-flat application, not N

_wohnungen_context was calling last_application_for_flat(uid, f.id)
inside the flats loop — at 100 flats that's 101 queries per poll, and
with running applications the page polls every 3s. New
db.latest_applications_by_flat(user_id) returns {flat_id: row} via a
single grouped self-join.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
EiSiMo 2026-04-21 19:06:48 +02:00
parent ebb11178e7
commit 77098c82df
2 changed files with 22 additions and 2 deletions

View file

@ -400,6 +400,9 @@ def _wohnungen_context(user) -> dict:
age_cutoff = None
if max_age_hours:
age_cutoff = datetime.now(timezone.utc) - timedelta(hours=int(max_age_hours))
# One query for this user's latest application per flat, instead of a
# per-flat query inside the loop.
latest_apps = db.latest_applications_by_flat(uid)
flats_view = []
for f in flats:
if f["id"] in rejected:
@ -417,8 +420,7 @@ def _wohnungen_context(user) -> dict:
"wbs": f["wbs"],
}, filters):
continue
last = db.last_application_for_flat(uid, f["id"])
flats_view.append({"row": f, "last": last})
flats_view.append({"row": f, "last": latest_apps.get(f["id"])})
rejected_view = db.rejected_flats(uid)
enrichment_counts = db.enrichment_counts()