Skip to content

Commit

Permalink
fix: migration 48
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Nov 16, 2023
1 parent 2f4a0e3 commit fbf9045
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 8 deletions.
26 changes: 18 additions & 8 deletions cfl_common/common/migrations/0048_unique_school_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,24 @@
def unique_school_names(apps: Apps, *args):
School = apps.get_model("common", "School")

schools = School.objects.values("name").annotate(name_count=models.Count("name")).filter(name_count__gt=1)
for school in schools:
schools = list(School.objects.filter(name=school["name"]).order_by("id"))
for index in range(school["name_count"]):
if index > 0:
school = schools[index]
school.name += f" {index + 1}"
school.save()
def get_school_name(school_name: str, school_name_number: int):
return f"{school_name} {school_name_number}"

school_values = School.objects.values("name").annotate(name_count=models.Count("name")).filter(name_count__gt=1)
for school_value in school_values:
school_name = school_value["name"]
school_name_number = 1

schools = list(School.objects.filter(name=school_name).order_by("id"))
for index in range(1, len(schools)):
school = schools[index]

school.name = get_school_name(school_name, school_name_number)
while School.objects.filter(name=school.name).exists():
school_name_number += 1
school.name = get_school_name(school_name, school_name_number)

school.save()


class Migration(migrations.Migration):
Expand Down
29 changes: 29 additions & 0 deletions cfl_common/common/tests/test_0048_unique_school_names.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import pytest
from django_test_migrations.migrator import Migrator


@pytest.mark.django_db
def test_0048_unique_school_names(migrator: Migrator):
state = migrator.apply_initial_migration(("common", "0047_delete_school_postcode"))
School = state.apps.get_model("common", "School")

school_name = "ExampleSchool"
School.objects.bulk_create(
[
School(name=school_name),
School(name=school_name),
School(name=f"{school_name} 1"),
]
)
school_ids = list(School.objects.order_by("-id")[:3].values_list("id", flat=True))
school_ids.reverse()

migrator.apply_tested_migration(("common", "0048_unique_school_names"))
School = state.apps.get_model("common", "School")

def assert_school_name(index: int, name: str):
assert School.objects.get(id=school_ids[index]).name == name

assert_school_name(0, school_name)
assert_school_name(1, f"{school_name} 2")
assert_school_name(2, f"{school_name} 1")

0 comments on commit fbf9045

Please sign in to comment.