layerindex/views.py: fix StatsView statistics page timeout
PATCH 1/5 layerindex/views.py: fix StatsView statistics page timeout
The per-branch statistics query used a single ORM queryset with five Count(..., distinct=True) annotations spanning deep reverse FK chains (layerbranch__recipe, layerbranch__bbclass, etc.). Django translates this into one SQL query with multiple LEFT OUTER JOINs across all those tables simultaneously. At production data volumes (~541 layers, ~25k recipes) the resulting query exhausts gunicorn worker memory/time, causing a 504 Gateway Time-out.
Fix by iterating over each visible branch individually and issuing simple COUNT queries per table. This replaces one huge cross-join with N×5 small indexed WHERE-clause queries that are far cheaper and independently cacheable.
The template is unchanged; Django's template engine resolves dict keys and object attributes identically with dot notation.
[YOCTO #15391]
AI-Generated: Claude Cowork Sonnet 4.6
--- layerindex/views.py | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-)
layerindex/views.py +17 -6
@@ -1522,12 +1522,23 @@ class StatsView(TemplateView): context['class_count_distinct'] = BBClass.objects.values('name').distinct().count() context['machine_count_distinct'] = Machine.objects.values('name').distinct().count() context['distro_count_distinct'] = Distro.objects.values('name').distinct().count() - context['perbranch'] = Branch.objects.filter(hidden=False).order_by('sort_priority').annotate( - layer_count=Count('layerbranch', distinct=True), - recipe_count=Count('layerbranch__recipe', distinct=True), - class_count=Count('layerbranch__bbclass', distinct=True), - machine_count=Count('layerbranch__machine', distinct=True), - distro_count=Count('layerbranch__distro', distinct=True)) + # Compute per-branch counts with individual queries rather than a single + # annotated queryset. The multi-Count(distinct=True) approach generates one + # large SQL query with many LEFT JOINs that causes a gunicorn worker timeout + # at production data volumes. Simple per-branch COUNT queries are far cheaper. + # See: https://bugzilla.yoctoproject.org/show_bug.cgi?id=15391 + perbranch = [] + for branch in Branch.objects.filter(hidden=False).order_by('sort_priority'): + perbranch.append({ + 'name': branch.name, + 'updates_enabled': branch.updates_enabled, + 'layer_count': LayerBranch.objects.filter(branch=branch).count(), + 'recipe_count': Recipe.objects.filter(layerbranch__branch=branch).count(), + 'class_count': BBClass.objects.filter(layerbranch__branch=branch).count(), + 'machine_count': Machine.objects.filter(layerbranch__branch=branch).count(), + 'distro_count': Distro.objects.filter(layerbranch__branch=branch).count(), + }) + context['perbranch'] = perbranch return context
Signature · 1 line
2.54.0
PATCH 2/5 tests: add StatsView tests
Add test_stats_view.py covering the StatsView statistics page:
- HTTP 200 response
- perbranch context is a list of dicts (not a queryset)
- hidden branches are excluded
- branches are sorted by sort_priority
- each dict contains all keys the template requires
- per-branch counts match test fixture data
- updates_enabled is correctly reflected per branch
- overall context keys (layercount, *_count_distinct) are present
[YOCTO #15391]
AI-Generated: Claude Cowork Sonnet 4.6
--- tests/test_stats_view.py | 164 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 tests/test_stats_view.py
tests/test_stats_view.py new file +164 -0
@@ -0,0 +1,164 @@ +# layerindex-web - tests for StatsView +# +# Copyright (C) 2026 Konsulko Group +# +# Licensed under the MIT license, see COPYING.MIT for details +# +# SPDX-License-Identifier: MIT + +# Tests for bug #15391 - Statistics page timeout +# https://bugzilla.yoctoproject.org/show_bug.cgi?id=15391 +# +# The fix replaces a single annotated queryset (which generated one huge SQL +# query with multiple COUNT(DISTINCT ...) JOINs) with per-branch individual +# COUNT queries that are much cheaper at production data volumes. + +import pytest +from django.test import TestCase +from django.urls import reverse + +from layerindex.models import (Branch, LayerItem, LayerBranch, Recipe, + BBClass, Machine, Distro) + + [email protected]_db +class TestStatsView(TestCase): + """Tests for StatsView (bug #15391 - statistics page timeout fix).""" + + def setUp(self): + # Create two visible branches with different sort priorities + self.branch1 = Branch.objects.create( + name='main', + bitbake_branch='master', + short_description='Main branch', + sort_priority=1, + hidden=False, + updates_enabled=True, + ) + self.branch2 = Branch.objects.create( + name='wrynose', + bitbake_branch='2.18', + short_description='Wrynose branch', + sort_priority=2, + hidden=False, + updates_enabled=False, + ) + # A hidden branch that should never appear in perbranch + self.branch_hidden = Branch.objects.create( + name='old-hidden', + bitbake_branch='1.0', + short_description='Old hidden branch', + sort_priority=99, + hidden=True, + updates_enabled=False, + ) + + # A layer + self.layer = LayerItem.objects.create( + name='meta-test', + status='P', + layer_type='A', + summary='Test layer', + description='A test layer', + vcs_url='git://example.com/meta-test.git', + ) + + # Wire up layerbranches + self.lb1 = LayerBranch.objects.create(layer=self.layer, branch=self.branch1) + self.lb2 = LayerBranch.objects.create(layer=self.layer, branch=self.branch2) + + # Add objects only to branch1 + Recipe.objects.create( + layerbranch=self.lb1, + filename='test_1.0.bb', + pn='test', + pv='1.0', + filepath='recipes-test', + ) + BBClass.objects.create( + layerbranch=self.lb1, + name='testclass', + ) + Machine.objects.create( + layerbranch=self.lb1, + name='qemux86', + description='QEMU x86 machine', + ) + Distro.objects.create( + layerbranch=self.lb1, + name='testdistro', + description='Test distro', + ) + + def test_stats_view_returns_200(self): + """StatsView should return HTTP 200.""" + response = self.client.get(reverse('stats')) + self.assertEqual(response.status_code, 200) + + def test_perbranch_is_list_of_dicts(self): + """perbranch context should be a list of dicts, not a queryset.""" + response = self.client.get(reverse('stats')) + perbranch = response.context['perbranch'] + self.assertIsInstance(perbranch, list) + for item in perbranch: + self.assertIsInstance(item, dict) + + def test_perbranch_excludes_hidden_branches(self): + """Hidden branches should not appear in perbranch.""" + response = self.client.get(reverse('stats')) + names = [b['name'] for b in response.context['perbranch']] + self.assertIn('main', names) + self.assertIn('wrynose', names) + self.assertNotIn('old-hidden', names) + + def test_perbranch_sorted_by_priority(self): + """Branches should be ordered by sort_priority.""" + response = self.client.get(reverse('stats')) + names = [b['name'] for b in response.context['perbranch']] + self.assertEqual(names, ['master', 'main', 'wrynose']) + + def test_perbranch_dict_has_required_keys(self): + """Each perbranch dict must contain all keys the template expects.""" + required_keys = {'name', 'updates_enabled', 'layer_count', + 'recipe_count', 'class_count', 'machine_count', 'distro_count'} + response = self.client.get(reverse('stats')) + for item in response.context['perbranch']: + self.assertTrue(required_keys.issubset(item.keys()), + f"Missing keys in perbranch item: {required_keys - item.keys()}") + + def test_perbranch_counts_branch1(self): + """Per-branch counts for branch1 should reflect the test data.""" + response = self.client.get(reverse('stats')) + branch1_data = next(b for b in response.context['perbranch'] if b['name'] == 'main') + self.assertEqual(branch1_data['layer_count'], 1) + self.assertEqual(branch1_data['recipe_count'], 1) + self.assertEqual(branch1_data['class_count'], 1) + self.assertEqual(branch1_data['machine_count'], 1) + self.assertEqual(branch1_data['distro_count'], 1) + + def test_perbranch_counts_branch2_empty(self): + """Branch2 has a layerbranch but no recipes/classes/machines/distros.""" + response = self.client.get(reverse('stats')) + branch2_data = next(b for b in response.context['perbranch'] if b['name'] == 'wrynose') + self.assertEqual(branch2_data['layer_count'], 1) + self.assertEqual(branch2_data['recipe_count'], 0) + self.assertEqual(branch2_data['class_count'], 0) + self.assertEqual(branch2_data['machine_count'], 0) + self.assertEqual(branch2_data['distro_count'], 0) + + def test_perbranch_updates_enabled_field(self): + """updates_enabled should be correctly reflected per branch.""" + response = self.client.get(reverse('stats')) + perbranch = response.context['perbranch'] + b1 = next(b for b in perbranch if b['name'] == 'main') + b2 = next(b for b in perbranch if b['name'] == 'wrynose') + self.assertTrue(b1['updates_enabled']) + self.assertFalse(b2['updates_enabled']) + + def test_overall_context_keys_present(self): + """Overall statistics context keys should all be present.""" + response = self.client.get(reverse('stats')) + for key in ('layercount', 'recipe_count_distinct', 'class_count_distinct', + 'machine_count_distinct', 'distro_count_distinct'): + self.assertIn(key, response.context, + f"Missing context key: {key}")
Signature · 1 line
2.54.0
PATCH 3/5 layerindex/views.py: fix DuplicatesView timeout
In reply to Tim OrlingTwo performance problems caused the duplicates page to take over 115 seconds to respond at production data volumes, eventually causing clients to disconnect (SIGPIPE / broken pipe):
1. Python list comprehension IN clause: each get_recipes/get_classes/ get_incfiles method evaluated its 'dupes' queryset in Python with a list comprehension to build a filter:
filter(pn__in=[item['pn'] for item in dupes])
This loaded all matching values into memory and emitted a potentially huge SQL IN (...) literal. Replace with a Django ORM subquery by passing the queryset directly:
filter(pn__in=dupes) # dupes is a .values('pn') queryset
Django translates this into a SQL subquery (WHERE pn IN (SELECT pn FROM ... GROUP BY pn HAVING COUNT(...) > 1)), which the database can optimise without a round-trip through Python.
2. N+1 queries: the template renders recipe.layerbranch.layer.name, class.layerbranch.layer.name and incfile.layerbranch.layer.name for every row. Without select_related these trigger one extra query per row. Add select_related('layerbranch__layer') to each queryset so the JOIN is done once up front.
[YOCTO #16175]
AI-Generated: Claude Cowork Sonnet 4.6
--- layerindex/views.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
layerindex/views.py +12 -6
@@ -656,24 +656,30 @@ class DuplicatesView(TemplateView): init_qs = Recipe.objects.filter(layerbranch__branch__name=self.kwargs['branch']) if layer_ids: init_qs = init_qs.filter(layerbranch__layer__in=layer_ids) - dupes = init_qs.values('pn').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1) - qs = init_qs.all().filter(pn__in=[item['pn'] for item in dupes]).order_by('pn', 'layerbranch__layer', '-pv') + # Use a subquery instead of a Python list comprehension so that Django + # emits a single SQL subquery rather than loading all duplicate pn values + # into memory and building a potentially huge IN (...) clause. + # See: https://bugzilla.yoctoproject.org/show_bug.cgi?id=16175 + dupes = init_qs.values('pn').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1).values('pn') + qs = init_qs.filter(pn__in=dupes).select_related('layerbranch__layer').order_by('pn', 'layerbranch__layer', '-pv') return recipes_preferred_count(qs) def get_classes(self, layer_ids): init_qs = BBClass.objects.filter(layerbranch__branch__name=self.kwargs['branch']) if layer_ids: init_qs = init_qs.filter(layerbranch__layer__in=layer_ids) - dupes = init_qs.values('name').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1) - qs = init_qs.all().filter(name__in=[item['name'] for item in dupes]).order_by('name', 'layerbranch__layer') + # Use a subquery instead of a Python list comprehension (see bug #16175) + dupes = init_qs.values('name').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1).values('name') + qs = init_qs.filter(name__in=dupes).select_related('layerbranch__layer').order_by('name', 'layerbranch__layer') return qs def get_incfiles(self, layer_ids): init_qs = IncFile.objects.filter(layerbranch__branch__name=self.kwargs['branch']) if layer_ids: init_qs = init_qs.filter(layerbranch__layer__in=layer_ids) - dupes = init_qs.values('path').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1) - qs = init_qs.all().filter(path__in=[item['path'] for item in dupes]).order_by('path', 'layerbranch__layer') + # Use a subquery instead of a Python list comprehension (see bug #16175) + dupes = init_qs.values('path').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1).values('path') + qs = init_qs.filter(path__in=dupes).select_related('layerbranch__layer').order_by('path', 'layerbranch__layer') return qs def get_context_data(self, **kwargs):
Signature · 1 line
2.54.0
PATCH 4/5 tests: add DuplicatesView tests
In reply to Tim OrlingAdd test_duplicates_view.py covering the DuplicatesView duplicates page:
- HTTP 200 response
- Duplicate recipes/classes/include files are included in context
- Unique (non-duplicate) objects are excluded from context
- Each duplicate appears once per layer (two rows for two layers)
- Layer filter (?l=id) restricts results to the selected layer, suppressing duplicates when only one layer is in scope
- Branch with no data returns empty querysets
- select_related check: accessing layerbranch.layer.name after list evaluation fires no additional queries
[YOCTO #16175]
AI-Generated: Claude Cowork Sonnet 4.6
--- tests/test_duplicates_view.py | 218 ++++++++++++++++++++++++++++++++++ 1 file changed, 218 insertions(+) create mode 100644 tests/test_duplicates_view.py
tests/test_duplicates_view.py new file +218 -0
@@ -0,0 +1,218 @@ +# layerindex-web - tests for DuplicatesView +# +# Copyright (C) 2026 Tim Orling <[email protected]> +# +# Licensed under the MIT license, see COPYING.MIT for details +# +# SPDX-License-Identifier: MIT + +# Tests for bug #16175 - Duplicates page timeout +# https://bugzilla.yoctoproject.org/show_bug.cgi?id=16175 +# +# The fix replaces Python list comprehensions used to build IN (...) clauses +# with Django ORM subqueries, and adds select_related to avoid N+1 queries +# when the template resolves layerbranch__layer names. + +import pytest +from django.test import TestCase +from django.urls import reverse + +from layerindex.models import (Branch, LayerItem, LayerBranch, Recipe, + BBClass, IncFile) + + [email protected]_db +class TestDuplicatesView(TestCase): + """Tests for DuplicatesView (bug #16175 - duplicates page timeout fix).""" + + def setUp(self): + self.branch = Branch.objects.create( + name='main', + bitbake_branch='master', + short_description='Main branch', + sort_priority=1, + hidden=False, + updates_enabled=True, + ) + + # Two layers — objects in both will appear as duplicates + self.layer_a = LayerItem.objects.create( + name='meta-alpha', + status='P', + layer_type='A', + summary='Alpha layer', + description='Alpha test layer', + vcs_url='git://example.com/meta-alpha.git', + ) + self.layer_b = LayerItem.objects.create( + name='meta-beta', + status='P', + layer_type='S', + summary='Beta layer', + description='Beta test layer', + vcs_url='git://example.com/meta-beta.git', + ) + # A third layer whose objects are unique (should NOT appear as duplicates) + self.layer_c = LayerItem.objects.create( + name='meta-gamma', + status='P', + layer_type='S', + summary='Gamma layer', + description='Gamma test layer', + vcs_url='git://example.com/meta-gamma.git', + ) + + self.lb_a = LayerBranch.objects.create(layer=self.layer_a, branch=self.branch) + self.lb_b = LayerBranch.objects.create(layer=self.layer_b, branch=self.branch) + self.lb_c = LayerBranch.objects.create(layer=self.layer_c, branch=self.branch) + + # Duplicate recipe (same pn in layer_a and layer_b) + Recipe.objects.create(layerbranch=self.lb_a, filename='shared_1.0.bb', + pn='shared', pv='1.0', filepath='recipes-test') + Recipe.objects.create(layerbranch=self.lb_b, filename='shared_1.0.bb', + pn='shared', pv='1.0', filepath='recipes-test') + # Unique recipe (only in layer_c — should NOT appear) + Recipe.objects.create(layerbranch=self.lb_c, filename='unique_1.0.bb', + pn='unique', pv='1.0', filepath='recipes-test') + + # Duplicate class (same name in layer_a and layer_b) + BBClass.objects.create(layerbranch=self.lb_a, name='sharedclass') + BBClass.objects.create(layerbranch=self.lb_b, name='sharedclass') + # Unique class (only in layer_c — should NOT appear) + BBClass.objects.create(layerbranch=self.lb_c, name='uniqueclass') + + # Duplicate include file (same path in layer_a and layer_b) + IncFile.objects.create(layerbranch=self.lb_a, path='conf/shared.inc') + IncFile.objects.create(layerbranch=self.lb_b, path='conf/shared.inc') + # Unique include file (only in layer_c — should NOT appear) + IncFile.objects.create(layerbranch=self.lb_c, path='conf/unique.inc') + + def _url(self, branch='main'): + return reverse('duplicates', kwargs={'branch': branch}) + + def test_duplicates_view_returns_200(self): + """DuplicatesView should return HTTP 200.""" + response = self.client.get(self._url()) + self.assertEqual(response.status_code, 200) + + # --- Recipes --- + + def test_duplicate_recipes_included(self): + """Recipes appearing in more than one layer should be in context.""" + response = self.client.get(self._url()) + pns = [r.pn for r in response.context['recipes']] + self.assertIn('shared', pns) + + def test_unique_recipes_excluded(self): + """Recipes appearing in only one layer should not appear.""" + response = self.client.get(self._url()) + pns = [r.pn for r in response.context['recipes']] + self.assertNotIn('unique', pns) + + def test_duplicate_recipes_have_two_rows(self): + """Each layer's entry for the duplicate recipe should be present.""" + response = self.client.get(self._url()) + shared = [r for r in response.context['recipes'] if r.pn == 'shared'] + self.assertEqual(len(shared), 2) + + # --- Classes --- + + def test_duplicate_classes_included(self): + """Classes appearing in more than one layer should be in context.""" + response = self.client.get(self._url()) + names = [c.name for c in response.context['classes']] + self.assertIn('sharedclass', names) + + def test_unique_classes_excluded(self): + """Classes appearing in only one layer should not appear.""" + response = self.client.get(self._url()) + names = [c.name for c in response.context['classes']] + self.assertNotIn('uniqueclass', names) + + def test_duplicate_classes_have_two_rows(self): + """Both layer entries for the duplicate class should be present.""" + response = self.client.get(self._url()) + shared = [c for c in response.context['classes'] if c.name == 'sharedclass'] + self.assertEqual(len(shared), 2) + + # --- Include files --- + + def test_duplicate_incfiles_included(self): + """Include files appearing in more than one layer should be in context.""" + response = self.client.get(self._url()) + paths = [f.path for f in response.context['incfiles']] + self.assertIn('conf/shared.inc', paths) + + def test_unique_incfiles_excluded(self): + """Include files appearing in only one layer should not appear.""" + response = self.client.get(self._url()) + paths = [f.path for f in response.context['incfiles']] + self.assertNotIn('conf/unique.inc', paths) + + def test_duplicate_incfiles_have_two_rows(self): + """Both layer entries for the duplicate include file should be present.""" + response = self.client.get(self._url()) + shared = [f for f in response.context['incfiles'] if f.path == 'conf/shared.inc'] + self.assertEqual(len(shared), 2) + + # --- Layer filter --- + + def test_layer_filter_restricts_recipes(self): + """Passing ?l=<layer_id> should restrict results to that layer.""" + response = self.client.get(self._url() + f'?l={self.layer_a.id}') + self.assertEqual(response.status_code, 200) + # With only one layer selected, nothing can be a duplicate + pns = [r.pn for r in response.context['recipes']] + self.assertNotIn('shared', pns) + + def test_wrong_branch_returns_empty(self): + """A branch with no data should return empty querysets.""" + other = Branch.objects.create( + name='other', + bitbake_branch='other', + sort_priority=50, + ) + response = self.client.get(reverse('duplicates', kwargs={'branch': 'other'})) + self.assertEqual(response.status_code, 200) + self.assertEqual(len(list(response.context['recipes'])), 0) + self.assertEqual(len(list(response.context['classes'])), 0) + self.assertEqual(len(list(response.context['incfiles'])), 0) + + def test_select_related_avoids_extra_queries(self): + """Ensure layerbranch and layer are fetched with select_related. + + Checks that accessing layerbranch.layer.name on query results does not + trigger additional database queries (i.e. select_related is working). + """ + from django.db import connection, reset_queries + from django.conf import settings + + settings.DEBUG = True + reset_queries() + + view = __import__('layerindex.views', fromlist=['DuplicatesView']).DuplicatesView + v = view() + v.kwargs = {'branch': 'main'} + v.request = None + + recipes = list(v.get_recipes([])) + classes = list(v.get_classes([])) + incfiles = list(v.get_incfiles([])) + + # Record query count after fetching + query_count_after_fetch = len(connection.queries) + + # Access layerbranch.layer.name on every result — should NOT fire new queries + for r in recipes: + _ = r.layerbranch.layer.name + for c in classes: + _ = c.layerbranch.layer.name + for f in incfiles: + _ = f.layerbranch.layer.name + + query_count_after_access = len(connection.queries) + settings.DEBUG = False + + self.assertEqual(query_count_after_fetch, query_count_after_access, + "Unexpected extra queries when accessing layerbranch.layer.name — " + "select_related may not be working")
Signature · 1 line
2.54.0
PATCH 5/5 layerindex/views.py: fix DuplicatesView 504 from per-row correlated subquery
In reply to Tim OrlingThe previous fix (subquery IN clause + select_related) resolved the Python memory overhead but the 504 Gateway Timeout persisted because recipes_preferred_count() uses .extra(select={...}) to embed a correlated multi-table subquery that the database evaluates once for every result row. With hundreds of duplicate recipes on the master branch this creates an O(N) compounding scan that dominates page load time.
Replace the call to recipes_preferred_count() in DuplicatesView.get_recipes with a two-step batch approach:
1. Fetch all duplicate recipes into a list using the existing subquery + select_related (one SQL query).
2. Run a single aggregating query to find, for each pn, the maximum index_preference among S/A-type layers in this branch that carry that pn (one SQL query returning one row per distinct pn).
3. Annotate each recipe object in Python: preferred_count is set to 1 if another S/A layer has a strictly higher index_preference for the same pn, otherwise 0. The template only checks preferred_count > 0, so the boolean semantics are identical to the original COUNT.
recipes_preferred_count() is intentionally left unchanged — it is still used by RecipeSearchView where result sets are paginated to 50 rows and the per-row cost is negligible.
Also add Max to the django.db.models import line.
[YOCTO #16175]
AI-Generated: Claude Cowork Sonnet 4.6
--- layerindex/views.py | 30 ++++++++- tests/test_duplicates_view.py | 113 ++++++++++++++++++++++------------ 2 files changed, 100 insertions(+), 43 deletions(-)
layerindex/views.py +27 -3
@@ -25,7 +25,7 @@ from django.contrib.sites.models import Site from django.core.exceptions import PermissionDenied from django.urls import resolve, reverse, reverse_lazy from django.db import transaction -from django.db.models import Count, Q +from django.db.models import Count, Max, Q from django.db.models.functions import Lower from django.db.models.query import QuerySet from django.db.models.signals import pre_save
@@ -661,8 +661,32 @@ class DuplicatesView(TemplateView): # into memory and building a potentially huge IN (...) clause. # See: https://bugzilla.yoctoproject.org/show_bug.cgi?id=16175 dupes = init_qs.values('pn').annotate(Count('layerbranch', distinct=True)).filter(layerbranch__count__gt=1).values('pn') - qs = init_qs.filter(pn__in=dupes).select_related('layerbranch__layer').order_by('pn', 'layerbranch__layer', '-pv') - return recipes_preferred_count(qs) + recipes = list(init_qs.filter(pn__in=dupes).select_related('layerbranch__layer').order_by('pn', 'layerbranch__layer', '-pv')) + if not recipes: + return recipes + # recipes_preferred_count() attaches a correlated subquery via .extra() that + # the database evaluates once per result row. With hundreds of duplicate + # recipes that compounds into a slow multi-table correlated scan that causes + # a 504 Gateway Timeout. Instead, compute preferred_count with a single + # batch MAX query across all pns and annotate the results in Python. + # + # A recipe is "non-preferred" (preferred_count > 0) when another layer of + # type S or A carries the same pn and has a higher index_preference. + pns = {r.pn for r in recipes} + pn_max_pref = dict( + Recipe.objects.filter( + layerbranch__branch__name=self.kwargs['branch'], + pn__in=pns, + layerbranch__layer__layer_type__in=['S', 'A'], + ).values('pn').annotate( + max_pref=Max('layerbranch__layer__index_preference') + ).values_list('pn', 'max_pref') + ) + for recipe in recipes: + own_pref = recipe.layerbranch.layer.index_preference + max_pref = pn_max_pref.get(recipe.pn) + recipe.preferred_count = 1 if (max_pref is not None and max_pref > own_pref) else 0 + return recipes def get_classes(self, layer_ids): init_qs = BBClass.objects.filter(layerbranch__branch__name=self.kwargs['branch'])
tests/test_duplicates_view.py +73 -40
206 lines not on this page · raw message
Signature · 1 line
2.54.0