From 305136d963da5b0bbbef1d8dc72cfdc06dc9b2ab Mon Sep 17 00:00:00 2001 From: Jean-Marie Favreau Date: Mon, 11 Nov 2024 11:25:10 +0100 Subject: [PATCH] Add a migration script to fix duplicated categories during database setup --- .../0108_remove_duplicated_categories.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/agenda_culturel/migrations/0108_remove_duplicated_categories.py diff --git a/src/agenda_culturel/migrations/0108_remove_duplicated_categories.py b/src/agenda_culturel/migrations/0108_remove_duplicated_categories.py new file mode 100644 index 0000000..b4627a1 --- /dev/null +++ b/src/agenda_culturel/migrations/0108_remove_duplicated_categories.py @@ -0,0 +1,44 @@ +# Generated by Django 4.2.9 on 2024-11-11 10:15 + +from django.db import migrations + + +def remove_duplicated_categories(apps, schema_editor): + Category = apps.get_model("agenda_culturel", "Category") + CategorisationRule = apps.get_model("agenda_culturel", "CategorisationRule") + Event = apps.get_model("agenda_culturel", "Event") + + + catnames = list(set([c.name for c in Category.objects.all()])) + + # for each category name + for cname in catnames: + # check if it exists more than one category + if Category.objects.filter(name=cname).count() > 1: + cats = Category.objects.filter(name=cname).order_by("pk") + nbs = [Event.objects.filter(category=c).count() + CategorisationRule.objects.filter(category=c).count() for c in cats] + + # if only one category with this name has elements + if len([n for n in nbs if n != 0]) == 1: + # remove all categories without elements + for n, c in zip(nbs, cats): + if n == 0: + c.delete() + else: + # otherwise, remove all but the last one (by ID) + for c in cats[0:-1]: + c.delete() + + +def do_nothing(apps, schema_editor): + pass + +class Migration(migrations.Migration): + + dependencies = [ + ('agenda_culturel', '0107_strip_aliases'), + ] + + operations = [ + migrations.RunPython(remove_duplicated_categories, reverse_code=do_nothing) + ]