Coverage for src/backend/InvenTree/build/migrations/0046_auto_20230606_1033.py: 36%
32 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 17:47 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 17:47 +0000
1# Generated by Django 3.2.19 on 2023-06-06 10:33
3import logging
5from django.db import migrations
8logger = logging.getLogger('inventree')
11def add_build_line_links(apps, schema_editor):
12 """Data migration to add links between BuildLine and BuildItem objects.
14 Associated model types:
15 Build: A "Build Order"
16 BomItem: An individual line in the BOM for Build.part
17 BuildItem: An individual stock allocation against the Build Order
18 BuildLine: (new model) an individual line in the Build Order
20 Goals:
21 - Find all BuildItem objects which are associated with a Build
22 - Link them against the relevant BuildLine object
23 - The BuildLine objects should have been created in 0044_auto_20230528_1410.py
24 """
26 BuildItem = apps.get_model("build", "BuildItem")
27 BuildLine = apps.get_model("build", "BuildLine")
29 # Find any existing BuildItem objects
30 build_items = BuildItem.objects.all()
32 n_missing = 0
34 for item in build_items: 34 ↛ 37line 34 didn't jump to line 37 because the loop on line 34 never started
36 # Find the relevant BuildLine object
37 line = BuildLine.objects.filter(
38 build=item.build,
39 bom_item=item.bom_item
40 ).first()
42 if line is None:
43 logger.warning(f"BuildLine does not exist for BuildItem {item.pk}")
44 n_missing += 1
46 if item.build is None or item.bom_item is None:
47 continue
49 # Create one!
50 line = BuildLine.objects.create(
51 build=item.build,
52 bom_item=item.bom_item,
53 quantity=item.bom_item.quantity * item.build.quantity
54 )
56 # Link the BuildItem to the BuildLine
57 # In the next data migration, we remove the 'build' and 'bom_item' fields from BuildItem
58 item.build_line = line
59 item.save()
61 if build_items.count() > 0: 61 ↛ 62line 61 didn't jump to line 62 because the condition on line 61 was never true
62 logger.info(f"add_build_line_links: Updated {build_items.count()} BuildItem objects (added {n_missing})")
65def reverse_build_links(apps, schema_editor):
66 """Reverse data migration from add_build_line_links
68 Basically, iterate through each BuildItem and update the links based on the BuildLine
69 """
71 BuildItem = apps.get_model("build", "BuildItem")
73 items = BuildItem.objects.all()
75 for item in items:
76 item.build = item.build_line.build
77 item.bom_item = item.build_line.bom_item
78 item.save()
80 if items.count() > 0:
81 logger.info(f"reverse_build_links: Updated {items.count()} BuildItem objects")
84class Migration(migrations.Migration):
86 dependencies = [
87 ('build', '0045_builditem_build_line'),
88 ]
90 operations = [
91 migrations.RunPython(
92 add_build_line_links,
93 reverse_code=reverse_build_links,
94 )
95 ]