diff --git a/arkindex/documents/migrations/0030_remove_entity_metatype.py b/arkindex/documents/migrations/0030_remove_entity_metatype.py index 47dddf05b4cdee213a8177a9f002ec2b23eff2be..c1c7e4aeca1e4ee7030e15bd6c58ffd16d8940e1 100644 --- a/arkindex/documents/migrations/0030_remove_entity_metatype.py +++ b/arkindex/documents/migrations/0030_remove_entity_metatype.py @@ -1,11 +1,14 @@ # Generated by Django 2.2 on 2019-12-13 10:28 from django.db import migrations +from arkindex_common.enums import EntityType from enum import Enum def remove_entity_metatype(apps, schema_editor): MetaData = apps.get_model('documents', 'MetaData') + if not MetaData.objects.exists(): + return class OldMetaType(Enum): Text = 'text' @@ -15,17 +18,25 @@ def remove_entity_metatype(apps, schema_editor): Reference = 'reference' Entity = 'entity' - values = set(item.value for item in OldMetaType) - # Don't try this at home MetaData._meta.fields[2].enum = OldMetaType - for metadata in MetaData.objects.filter(type=OldMetaType.Entity).prefetch_related('entity'): - metadata_type = OldMetaType.Text - if metadata.entity and metadata.entity.type.value in values: - metadata_type = OldMetaType(metadata.entity.type.value) - metadata.type = metadata_type - metadata.save() + MetaData.objects.filter(type=OldMetaType.Entity, entity__type=EntityType.Location).update(type=OldMetaType.Location) + MetaData.objects.filter(type=OldMetaType.Entity, entity__type=EntityType.Date).update(type=OldMetaType.Date) + MetaData.objects.filter(type=OldMetaType.Entity).update(type=OldMetaType.Text) + + +def add_entity_metatype(apps, schema_editor): + MetaData = apps.get_model('documents', 'MetaData') + if not MetaData.objects.exists(): + return + + class OldMetaType(Enum): + Entity = 'entity' + + # Don't try this at home + MetaData._meta.fields[2].enum = OldMetaType + MetaData.objects.exclude(entity__isnull=True).update(type=OldMetaType.Entity) class Migration(migrations.Migration): @@ -35,8 +46,5 @@ class Migration(migrations.Migration): ] operations = [ - migrations.RunPython( - remove_entity_metatype, - reverse_code=migrations.RunPython.noop - ), + migrations.RunPython(remove_entity_metatype, add_entity_metatype), ]