diff --git a/InvenTree/build/migrations/0030_alter_build_reference.py b/InvenTree/build/migrations/0030_alter_build_reference.py new file mode 100644 index 0000000000..75f43c77dc --- /dev/null +++ b/InvenTree/build/migrations/0030_alter_build_reference.py @@ -0,0 +1,20 @@ +# Generated by Django 3.2.4 on 2021-07-08 14:14 + +import InvenTree.validators +import build.models +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('build', '0029_auto_20210601_1525'), + ] + + operations = [ + migrations.AlterField( + model_name='build', + name='reference', + field=models.CharField(default=build.models.get_next_build_number, help_text='Build Order Reference', max_length=64, unique=True, validators=[InvenTree.validators.validate_build_order_reference], verbose_name='Reference'), + ), + ] diff --git a/InvenTree/build/models.py b/InvenTree/build/models.py index 848d774d1c..f1190a6346 100644 --- a/InvenTree/build/models.py +++ b/InvenTree/build/models.py @@ -37,6 +37,35 @@ from part import models as PartModels from users import models as UserModels +def get_next_build_number(): + """ + Returns the next available BuildOrder reference number + """ + + if Build.objects.count() == 0: + return + + build = Build.objects.exclude(reference=None).last() + + attempts = set([build.reference]) + + reference = build.reference + + while 1: + reference = increment(build.reference) + + if reference in attempts: + # Escape infinite recursion + return reference + + if Build.objects.filter(reference=reference).exists(): + attempts.add(reference) + else: + break + + return reference + + class Build(MPTTModel): """ A Build object organises the creation of new StockItem objects from other existing StockItem objects. @@ -130,6 +159,7 @@ class Build(MPTTModel): blank=False, help_text=_('Build Order Reference'), verbose_name=_('Reference'), + default=get_next_build_number, validators=[ validate_build_order_reference ]