BOM annotate fix (#13396)

* Annotation improvements for BOMItem serializer

Significant speed improvements for BOMItem API

* Fix type hinting

* adjust test
This commit is contained in:
Oliver authored and GitHub committed 2026-11-27 13:45:52 +11:00
1 parent 9d8510327a
commit 79e4a50530
5 files changed
+183 -95

No files matched your search

+3 -35
View File
@@ -6,16 +6,7 @@ from typing import Optional
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import models, transaction
from django.db.models import (
BooleanField,
Case,
ExpressionWrapper,
F,
FloatField,
Q,
Value,
When,
)
from django.db.models import BooleanField, Case, ExpressionWrapper, F, Q, Value, When
from django.db.models.functions import Coalesce, Greatest
from django.utils.translation import gettext_lazy as _
@@ -1682,32 +1673,9 @@ class BuildLineSerializer(
)
# Annotate the queryset with 'available variant stock' information
variant_stock_query = part.filters.variant_stock_query(
reference='bom_item__sub_part__', filter=stock_filter
)
queryset = queryset.alias(
variant_stock_total=part.filters.annotate_variant_quantity(
variant_stock_query, reference='quantity'
),
variant_bo_allocations=part.filters.annotate_variant_quantity(
variant_stock_query, reference='sales_order_allocations__quantity'
),
variant_so_allocations=part.filters.annotate_variant_quantity(
variant_stock_query, reference='allocations__quantity'
),
)
queryset = queryset.annotate(
available_variant_stock=Greatest(
ExpressionWrapper(
F('variant_stock_total')
- F('variant_bo_allocations')
- F('variant_so_allocations'),
output_field=FloatField(),
),
0,
output_field=FloatField(),
available_variant_stock=part.filters.annotate_available_variant_stock(
reference='bom_item__sub_part__', filter=stock_filter
)
)
+70 -1
View File
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from typing import Optional
from django.db import connection
from django.db.models import Sum
from django.db.models import F, Sum
from django.test.utils import CaptureQueriesContext
from django.urls import reverse
@@ -1914,6 +1914,75 @@ class BuildLineTests(BuildAPITest):
self.assertIn(name, allocation)
self.assertNotIn('default', allocation[name])
def test_available_variant_stock(self):
"""Test the 'available_variant_stock' annotation for BuildLine objects."""
# Select a BuildLine whose BOM item belongs to the part being built
# (not every fixture BuildLine is consistent with its build),
# and whose sub_part is not trackable (allocations would require a build output)
line = (
BuildLine.objects
.filter(
bom_item__sub_part__isnull=False,
bom_item__sub_part__trackable=False,
bom_item__part=F('build__part'),
)
.order_by('pk')
.first()
)
assert line is not None
# Variant stock can only be allocated if the BOM item allows variants
line.bom_item.allow_variants = True
line.bom_item.save()
url = reverse('api-build-line-detail', kwargs={'pk': line.pk})
sub_part = line.bom_item.sub_part
initial = self.get(url, expected_code=200).data['available_variant_stock']
# Create some variants of the referenced sub_part, with stock
sub_part.is_template = True
sub_part.save()
variant_stock = []
for idx in range(3):
variant = Part.objects.create(
name=f'Variant {idx}',
description='A variant part',
variant_of=sub_part,
component=True,
)
variant_stock.append(StockItem.objects.create(part=variant, quantity=100))
data = self.get(url, expected_code=200).data
self.assertEqual(data['available_variant_stock'], initial + 300)
# Allocate some variant stock - this reduces the available variant stock
BuildItem.objects.create(
build_line=line, stock_item=variant_stock[0], quantity=40
)
data = self.get(url, expected_code=200).data
self.assertEqual(data['available_variant_stock'], initial + 260)
# Stock for a variant-of-a-variant is also counted
parent_variant = variant_stock[1].part
parent_variant.is_template = True
parent_variant.save()
nested = Part.objects.create(
name='Nested variant',
description='A variant of a variant',
variant_of=variant_stock[1].part,
component=True,
)
StockItem.objects.create(part=nested, quantity=7)
data = self.get(url, expected_code=200).data
self.assertEqual(data['available_variant_stock'], initial + 267)
def test_consumed_read_only(self):
"""The 'consumed' quantity cannot be changed via the BuildLine API.
+59 -52
View File
@@ -109,23 +109,19 @@ def annotate_on_order_quantity(reference: str = '') -> QuerySet:
order__status__in=PurchaseOrderStatusGroups.OPEN, quantity__gt=F('received')
)
# Note: A single subquery is used to calculate the outstanding (quantity - received) amount
return Greatest(
Coalesce(
SubquerySum(
ExpressionWrapper(
F(f'{reference}supplier_parts__purchase_order_line_items__quantity')
* F(f'{reference}supplier_parts__pack_quantity_native'),
output_field=DecimalField(),
),
filter=order_filter,
),
Decimal(0),
output_field=DecimalField(),
)
- Coalesce(
SubquerySum(
ExpressionWrapper(
F(f'{reference}supplier_parts__purchase_order_line_items__received')
(
F(
f'{reference}supplier_parts__purchase_order_line_items__quantity'
)
- F(
f'{reference}supplier_parts__purchase_order_line_items__received'
)
)
* F(f'{reference}supplier_parts__pack_quantity_native'),
output_field=DecimalField(),
),
@@ -333,11 +329,13 @@ def variant_stock_query(reference: str = '', filter: Optional[Q] = None) -> Quer
).filter(stock_filter)
def annotate_variant_quantity(subquery: Q, reference: str = 'quantity') -> QuerySet:
def annotate_variant_quantity(
subquery: QuerySet, reference: str = 'quantity'
) -> Coalesce:
"""Create a subquery annotation for all variant part stock items on the given parent query.
Args:
subquery: A 'variant_stock_query' Q object
subquery: A 'variant_stock_query' QuerySet
reference: The relationship reference of the variant stock items from the current queryset
"""
return Coalesce(
@@ -354,6 +352,45 @@ def annotate_variant_quantity(subquery: Q, reference: str = 'quantity') -> Query
)
def annotate_available_variant_stock(
reference: str = '', filter: Optional[Q] = None
) -> Case:
"""Annotate the total 'available' stock quantity for all variants of a part.
available_variant_stock = variant_stock - variant_allocations
Arguments:
reference: The relationship reference of the part from the current model (e.g. 'sub_part__')
filter: Q object which defines how to filter the variant stock items
Notes:
Variant parts are the descendants of a part in the variant tree (MPTT),
so a part can only have variant stock if (rght - lft) > 1.
The variant subqueries are only evaluated for such parts,
which avoids running three correlated subqueries for every row.
"""
vq = variant_stock_query(reference=reference, filter=filter)
available = Greatest(
ExpressionWrapper(
annotate_variant_quantity(vq, reference='quantity')
- annotate_variant_quantity(
vq, reference='sales_order_allocations__quantity'
)
- annotate_variant_quantity(vq, reference='allocations__quantity'),
output_field=FloatField(),
),
0,
output_field=FloatField(),
)
return Case(
When(Q(**{f'{reference}rght__gt': F(f'{reference}lft') + 1}), then=available),
default=Value(0.0),
output_field=FloatField(),
)
def annotate_category_parts() -> QuerySet:
"""Construct a queryset annotation which returns the number of parts in a particular category.
@@ -444,21 +481,13 @@ def annotate_bom_item_can_build(queryset: QuerySet, reference: str = '') -> Quer
And then finally, annotate the 'can_build' quantity for each BomItem:
"""
# Pre-fetch the required related fields
queryset = queryset.prefetch_related(
f'{reference}sub_part',
f'{reference}sub_part__stock_items',
f'{reference}sub_part__stock_items__allocations',
f'{reference}sub_part__stock_items__sales_order_allocations',
f'{reference}substitutes',
f'{reference}substitutes__part__stock_items',
)
# Queryset reference to the linked sub_part instance
sub_part_ref = f'{reference}sub_part__'
# Apply some aliased annotations to the queryset
queryset = queryset.annotate(
# Note: These are aliased (not annotated), as they are only used to calculate 'available_stock'.
# Annotating them would add a further copy of each (expensive) subquery to the SELECT clause.
queryset = queryset.alias(
# Total stock quantity (just for the sub_part itself)
total_stock=annotate_total_stock(sub_part_ref),
# Total allocated to sales orders
@@ -481,31 +510,9 @@ def annotate_bom_item_can_build(queryset: QuerySet, reference: str = '') -> Quer
)
)
# Annotate the total stock for any variant parts
vq = variant_stock_query(reference=sub_part_ref)
queryset = queryset.alias(
variant_stock_total=annotate_variant_quantity(vq, reference='quantity'),
variant_bo_allocations=annotate_variant_quantity(
vq, reference='sales_order_allocations__quantity'
),
variant_so_allocations=annotate_variant_quantity(
vq, reference='allocations__quantity'
),
)
# Annotate total variant stock
# Annotate the total available stock for any variant parts
queryset = queryset.annotate(
available_variant_stock=Greatest(
ExpressionWrapper(
F('variant_stock_total')
- F('variant_bo_allocations')
- F('variant_so_allocations'),
output_field=FloatField(),
),
0,
output_field=FloatField(),
)
available_variant_stock=annotate_available_variant_stock(reference=sub_part_ref)
)
# Account for substitute parts
@@ -538,7 +545,7 @@ def annotate_bom_item_can_build(queryset: QuerySet, reference: str = '') -> Quer
# Now we can annotate the total "available" stock for the BomItem
queryset = queryset.alias(
total_stock=ExpressionWrapper(
total_available_stock=ExpressionWrapper(
F('available_variant_stock')
+ F('available_substitute_stock')
+ F('available_stock'),
@@ -552,7 +559,7 @@ def annotate_bom_item_can_build(queryset: QuerySet, reference: str = '') -> Quer
ExpressionWrapper(
Case(
When(Q(quantity=0), then=Value(0)),
default=(F('total_stock') - F('setup_quantity'))
default=(F('total_available_stock') - F('setup_quantity'))
/ (
F('quantity')
* F('piece_count')
+2 -7
View File
@@ -1516,7 +1516,6 @@ class BomItemSerializer(
prefetch_fields=[
'substitutes',
'substitutes__part',
'substitutes__part__stock_items',
'substitutes__part__pricing_data',
],
)
@@ -1677,18 +1676,14 @@ class BomItemSerializer(
"""
# Prefetch related fields
# Note: Stock and allocation quantities are provided by annotations below,
# so there is no need to prefetch (potentially very large) related stock data
queryset = queryset.prefetch_related(
'part',
'part__category',
'part__stock_items',
'sub_part',
'sub_part__builds',
'sub_part__category',
'sub_part__pricing_data',
'sub_part__stock_items',
'sub_part__stock_items__allocations',
'sub_part__stock_items__sales_order_allocations',
'sub_part__stock_items__transfer_order_allocations',
)
# Annotate with the 'total pricing' information based on unit pricing and quantity
+49
View File
@@ -3476,6 +3476,55 @@ class BomItemTest(InvenTreeAPITestCase):
self.assertEqual(response.data['available_variant_stock'], 1000)
def test_bom_list_stock_scaling(self):
"""BOM list queries must not scale with the amount of stock for each component.
Stock quantities are provided via queryset annotations,
so stock items (and their allocations) must not be prefetched.
"""
url = reverse('api-bom-list')
params = {
'part': 100,
'substitutes': True,
'sub_part_detail': True,
'part_detail': True,
'pricing': True,
}
bom_items = list(BomItem.objects.filter(part=100))
self.assertGreater(len(bom_items), 0)
# Warm up any caches
self.get(url, params, expected_code=200)
with CaptureQueriesContext(connection) as ctx:
response = self.get(url, params, expected_code=200)
initial_stock = {row['pk']: row['available_stock'] for row in response.data}
# Create a large number of additional stock items for each component
StockItem.objects.bulk_create([
StockItem(part=item.sub_part, quantity=5)
for item in bom_items
for _ in range(25)
])
with CaptureQueriesContext(connection) as ctx2:
response = self.get(url, params, expected_code=200)
self.assertEqual(len(ctx2), len(ctx))
for query in ctx2.captured_queries:
self.assertFalse(
query['sql'].startswith('SELECT "stock_stockitem"'),
f'Unexpected stock item query: {query["sql"][:200]}',
)
# The annotated stock quantities reflect the new stock items
for row in response.data:
self.assertEqual(row['available_stock'], initial_stock[row['pk']] + 125)
def test_bom_export(self):
"""Test for exporting BOM data."""
url = reverse('api-bom-list')