Skip to content

Commit 9bfbdf5

Browse files
[#311] Fix migrations
1 parent 7ed53f9 commit 9bfbdf5

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/openklant/components/klantinteracties/migrations/0026_alter_betrokkene_bezoekadres_land_and_more.py

+64
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,68 @@
11
# Generated by Django 4.2.17 on 2025-01-27 14:35
22

3+
import logging
34
import django.core.validators
5+
import openklant.utils.validators
46
from django.db import migrations, models
57
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)
666

767

868
class Migration(migrations.Migration):
@@ -15,6 +75,10 @@ class Migration(migrations.Migration):
1575
]
1676

1777
operations = [
78+
migrations.RunPython(
79+
code=_check_and_update_records,
80+
reverse_code=migrations.RunPython.noop,
81+
),
1882
migrations.AlterField(
1983
model_name="betrokkene",
2084
name="bezoekadres_land",

0 commit comments

Comments
 (0)