Custom migration to find BomItem / BuildItem links where they exist

This commit is contained in:
Oliver Walters 2021-06-01 15:39:21 +10:00
parent 7578cab9a8
commit ab16e1efc3

View File

@ -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),
]