# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion def create_categories(apps, schema_editor): # Insert the previously hardcoded categories in the database Category = apps.get_model("partitions", "Category") Category.objects.bulk_create([ Category(name="Partitions actives", order=1), Category(name="Partitions optionnelles", order=2), Category(name="Partitions à venir", order=3), Category(name="Archives", order=4) ]) def set_new_categories(apps, schema_editor): Category = apps.get_model("partitions", "Category") PartitionSet = apps.get_model("partitions", "PartitionSet") assoc_list = Category.objects.order_by("order") mapping = { "active": assoc_list[0], "incoming": assoc_list[2], "old": assoc_list[3], "optional": assoc_list[1] } for par_set in PartitionSet.objects.all(): par_set.category = mapping[par_set.category_old] par_set.save() def reset_old_categories(apps, schema_editor): Category = apps.get_model("partitions", "Category") PartitionSet = apps.get_model("partition", "PartitionSet") assoc_list = Category.values_list("order", "id").order_by("order") mapping = { assoc_list[0][1]: "active", assoc_list[2][1]: "incoming", assoc_list[3][1]: "old", assoc_list[1][1]: "optional" } for par_set in PartitionSet.objects.all(): par_set.category_old = mapping[par_set.category] par_set.save() class Migration(migrations.Migration): dependencies = [ ('partitions', '0001_initial'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('name', models.CharField(max_length=127)), ('order', models.IntegerField(verbose_name='order')), ], options={'verbose_name': 'catégorie', 'verbose_name_plural': 'catégories'}, ), migrations.RunPython(create_categories, migrations.RunPython.noop), migrations.RenameField(model_name="partitionset", old_name="category", new_name="category_old"), migrations.AddField( model_name='partitionset', name='category', field=models.ForeignKey( verbose_name='Type de partition', to='partitions.Category', on_delete=django.db.models.deletion.PROTECT, default=1 # Dummy, will be set by the RunPython operation ), preserve_default=False, ), migrations.RunPython(set_new_categories, migrations.RunPython.noop), migrations.RemoveField(model_name="partitionset", name="category_old"), ]