1
1
# Generated by Django 4.2.17 on 2025-01-27 14:35
2
2
3
+ import logging
3
4
import django .core .validators
5
+ import openklant .utils .validators
4
6
from django .db import migrations , models
5
7
import openklant .utils .validators
8
+ from django .core .management import CommandError
9
+ from openklant .utils .constants import COUNTRIES_DICT
10
+
11
+ logger = logging .getLogger (__name__ )
12
+
13
+ FIELDS = ["bezoekadres_land" , "correspondentieadres_land" ]
14
+
15
+
16
+ def _check_records (records , model_name ):
17
+ total_failed_records = 0
18
+ for record in records :
19
+ record_failed = False
20
+ for field_name in FIELDS :
21
+ field_value = getattr (record , field_name , None )
22
+ iso_code = COUNTRIES_DICT .get (field_value , "" )
23
+ if field_value and not iso_code :
24
+ record_failed = True
25
+ logger .warning (
26
+ "%s(pk=%s, uuid=%s) Field: '%s'. No match found for nl_code: '%s'" ,
27
+ model_name ,
28
+ record .pk ,
29
+ record .uuid ,
30
+ field_name ,
31
+ field_value ,
32
+ )
33
+
34
+ if record_failed :
35
+ total_failed_records += 1
36
+ return total_failed_records
37
+
38
+
39
+ def _update_records (records ):
40
+ for record in records :
41
+ updated = False
42
+ for field_name in FIELDS :
43
+ if field_value := getattr (record , field_name , None ):
44
+ iso_code = COUNTRIES_DICT .get (field_value , "" )
45
+ setattr (record , field_name , iso_code )
46
+ updated = True
47
+
48
+ if updated :
49
+ record .save ()
50
+
51
+
52
+ def _check_and_update_records (apps , schema_editor ):
53
+ Betrokkene = apps .get_model ("klantinteracties" , "Betrokkene" )
54
+ Partij = apps .get_model ("klantinteracties" , "Partij" )
55
+
56
+ for model_name , model in [("Betrokkene" , Betrokkene ), ("Partij" , Partij )]:
57
+ records = model .objects .all ()
58
+ if total_failed_records := _check_records (records , model_name ):
59
+ raise CommandError (
60
+ "The migration cannot proceed due to %s records that don't comply with the %s model's requirements. "
61
+ "Possible data inconsistency or mapping error."
62
+ % (total_failed_records , model_name )
63
+ )
64
+ else :
65
+ _update_records (records )
6
66
7
67
8
68
class Migration (migrations .Migration ):
@@ -15,6 +75,10 @@ class Migration(migrations.Migration):
15
75
]
16
76
17
77
operations = [
78
+ migrations .RunPython (
79
+ code = _check_and_update_records ,
80
+ reverse_code = migrations .RunPython .noop ,
81
+ ),
18
82
migrations .AlterField (
19
83
model_name = "betrokkene" ,
20
84
name = "bezoekadres_land" ,
0 commit comments