Coverage for src/backend/InvenTree/stock/migrations/0118_auto_20260205_1218.py: 30%

34 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 17:47 +0000

1# Generated by Django 5.2.10 on 2026-02-05 12:18 

2 

3from django.db import migrations 

4 

5 

6def add_part_links(apps, schema_editor): 

7 """Add links to the Part model for all existing StockItemTracking entries.""" 

8 

9 StockItemTracking = apps.get_model('stock', 'StockItemTracking') 

10 

11 history_entries = [] 

12 

13 N = StockItemTracking.objects.count() 

14 

15 if N > 0: 15 ↛ 16line 15 didn't jump to line 16 because the condition on line 15 was never true

16 print(f"\nUpdating {N} StockItemTracking entries with part links...") 

17 

18 for tracking in StockItemTracking.objects.filter(part__isnull=True).select_related('item__part'): 18 ↛ 20line 18 didn't jump to line 20 because the loop on line 18 never started

19 

20 item = tracking.item 

21 

22 # No item link - skip 

23 if item is None: 

24 continue 

25 

26 part = item.part 

27 

28 # No part link - skip 

29 if part is None: 

30 continue 

31 

32 # Already linked to the correct part - skip 

33 if tracking.part == part: 

34 continue 

35 

36 tracking.part = part 

37 history_entries.append(tracking) 

38 

39 # Process in batches to avoid issues with very large datasets 

40 if len(history_entries) >= 100: 

41 StockItemTracking.objects.bulk_update(history_entries, ['part']) 

42 history_entries = [] 

43 print(".", end='', flush=True) 

44 

45 if len(history_entries) > 0: 45 ↛ 46line 45 didn't jump to line 46 because the condition on line 45 was never true

46 StockItemTracking.objects.bulk_update(history_entries, ['part']) 

47 

48 

49def remove_null_items(apps, schema_editor): 

50 """Reverse migration - remove any StockItemTracking entries which have a null item link.""" 

51 

52 StockItemTracking = apps.get_model('stock', 'StockItemTracking') 

53 

54 null_items = StockItemTracking.objects.filter(item__isnull=True) 

55 

56 count = null_items.count() 

57 

58 if count > 0: 

59 null_items.delete() 

60 print(f"\nDeleted {count} StockItemTracking entries with null item links") 

61 

62class Migration(migrations.Migration): 

63 

64 dependencies = [ 

65 ("stock", "0117_stockitemtracking_part_alter_stockitemtracking_item"), 

66 ] 

67 

68 operations = [ 

69 migrations.RunPython( 

70 add_part_links, 

71 reverse_code=remove_null_items, 

72 ) 

73 ]