2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-07-06 05:30:56 +00:00

Refactor previous code for looking up "previous" and "next" serial numbers

- Old way was extremely inefficient, especially when large spaces existed between serial numbers
- New method reduces O(n) to O(1)
This commit is contained in:
Oliver
2022-03-07 13:47:38 +11:00
parent d9f73ae05b
commit 2f3f57148a
2 changed files with 56 additions and 34 deletions

View File

@ -273,6 +273,55 @@ class StockItem(MPTTModel):
self.serial_int = serial_int
def get_next_serial_number(self, include_variants=True, reverse=False):
"""
Get the "next" serial number for the part this stock item references.
e.g. if this stock item has a serial number 100, we may return the stock item with serial number 101
Note that this only works for "serialized" stock items with integer values
Args:
include_variants: True if we wish to include stock for variant parts
reverse: True if we want to return the "previous" (lower) serial number
Returns:
A StockItem object matching the requirements, or None
"""
if not self.serialized:
return None
# Find only serialized stock items
items = StockItem.objects.exclude(serial=None).exclude(serial='')
if include_variants:
# Match against any part within the variant tree
items = items.filter(part__tree_id=self.part.tree_id)
else:
# Match only against the specific part
items = items.filter(part=self.part)
serial = self.serial_int
if reverse:
# Select only stock items with lower serial numbers, in decreasing order
items = items.filter(serial_int__lt=serial)
items = items.order_by('-serial_int')
else:
# Select only stock items with higher serial numbers, in increasing order
items = items.filter(serial_int__gt=serial)
items = items.order_by('serial_int')
if items.count() > 0:
item = items.first()
if item.serialized:
return item
return None
def save(self, *args, **kwargs):
"""
Save this StockItem to the database. Performs a number of checks: