diff --git a/InvenTree/build/migrations/0029_auto_20210601_1525.py b/InvenTree/build/migrations/0029_auto_20210601_1525.py new file mode 100644 index 0000000000..c5ea04b5c9 --- /dev/null +++ b/InvenTree/build/migrations/0029_auto_20210601_1525.py @@ -0,0 +1,62 @@ +# Generated by Django 3.2 on 2021-06-01 05:25 + +from django.db import migrations + + +def assign_bom_items(apps, schema_editor): + """ + Run through existing BuildItem objects, + and assign a matching BomItem + """ + + BuildItem = apps.get_model('build', 'builditem') + BomItem = apps.get_model('part', 'bomitem') + Part = apps.get_model('part', 'part') + + print("Assigning BomItems to existing BuildItem objects") + + count_valid = 0 + count_total = 0 + + for build_item in BuildItem.objects.all(): + + # Try to find a BomItem which matches the BuildItem + # Note: Before this migration, variant stock assignment was not allowed, + # so BomItem lookup should be pretty easy + + count_total += 1 + + try: + bom_item = BomItem.objects.get( + part__id=build_item.build.part.pk, + sub_part__id=build_item.stock_item.part.pk, + ) + + build_item.bom_item = bom_item + build_item.save() + + count_valid += 1 + + except BomItem.DoesNotExist: + pass + + print(f"Assigned BomItem for {count_valid}/{count_total} entries") + + +def unassign_bom_items(apps, schema_editor): + """ + Reverse migration does not do anything. + Function here to preserve ability to reverse migration + """ + pass + + +class Migration(migrations.Migration): + + dependencies = [ + ('build', '0028_builditem_bom_item'), + ] + + operations = [ + migrations.RunPython(assign_bom_items, reverse_code=unassign_bom_items), + ]