Coverage for src/backend/InvenTree/build/migrations/0044_auto_20230528_1410.py: 40%
34 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-05-28 14:10
3from django.db import migrations
6def get_bom_items_for_part(part, Part, BomItem):
7 """ Return a list of all BOM items for a given part.
9 Note that we cannot use the ORM here (as we are inside a data migration),
10 so we *copy* the logic from the Part class.
12 This is a snapshot of the Part.get_bom_items() method as of 2023-05-29
13 """
15 bom_items = set()
17 # Get all BOM items which directly reference the part
18 for bom_item in BomItem.objects.filter(part=part):
19 bom_items.add(bom_item)
21 # Get all BOM items which are inherited by the part
22 parents = Part.objects.filter(
23 tree_id=part.tree_id,
24 level__lt=part.level,
25 lft__lt=part.lft,
26 rght__gt=part.rght
27 )
29 for bom_item in BomItem.objects.filter(part__in=parents, inherited=True):
30 bom_items.add(bom_item)
32 return list(bom_items)
35def add_lines_to_builds(apps, schema_editor):
36 """Create BuildOrderLine objects for existing build orders"""
38 # Get database models
39 Build = apps.get_model("build", "Build")
40 BuildLine = apps.get_model("build", "BuildLine")
42 Part = apps.get_model("part", "Part")
43 BomItem = apps.get_model("part", "BomItem")
45 build_lines = []
47 builds = Build.objects.all()
49 if builds.count() > 0: 49 ↛ 50line 49 didn't jump to line 50 because the condition on line 49 was never true
50 print(f"Creating BuildOrderLine objects for {builds.count()} existing builds")
52 for build in builds: 52 ↛ 55line 52 didn't jump to line 55 because the loop on line 52 never started
53 # Create a BuildOrderLine for each BuildItem
55 bom_items = get_bom_items_for_part(build.part, Part, BomItem)
57 for item in bom_items:
58 build_lines.append(
59 BuildLine(
60 build=build,
61 bom_item=item,
62 quantity=item.quantity * build.quantity,
63 )
64 )
66 if len(build_lines) > 0: 66 ↛ 68line 66 didn't jump to line 68 because the condition on line 66 was never true
67 # Construct the new BuildLine objects
68 BuildLine.objects.bulk_create(build_lines)
69 print(f"Created {len(build_lines)} BuildOrderLine objects for existing builds")
72def remove_build_lines(apps, schema_editor):
73 """Remove BuildOrderLine objects from the database"""
75 # Get database models
76 BuildLine = apps.get_model("build", "BuildLine")
78 n = BuildLine.objects.all().count()
80 BuildLine.objects.all().delete()
82 if n > 0:
83 print(f"Removed {n} BuildOrderLine objects")
86class Migration(migrations.Migration):
88 dependencies = [
89 ('build', '0043_buildline'),
90 ]
92 operations = [
93 migrations.RunPython(
94 add_lines_to_builds,
95 reverse_code=remove_build_lines,
96 ),
97 ]