diff --git a/legacy/migration.py b/legacy/migration.py index d054ef7eb..7f004869b 100644 --- a/legacy/migration.py +++ b/legacy/migration.py @@ -25,6 +25,8 @@ appconfs = [apps.get_app_config(n) for n in [ 'lexml', 'protocoloadm', ]] +stubs_list = [] + name_sets = [set(m.__name__ for m in ac.get_models()) for ac in appconfs] # apps do not overlap @@ -103,6 +105,8 @@ def get_fk_related(field, value, label=None): warn(msg + ' => using NONE for zero value') else: value = make_stub(field.related_model, value) + stubs_list.append( + (value.id, field.model, field.related_model, field.name)) warn(msg + ' => STUB CREATED') else: assert value @@ -193,6 +197,8 @@ class DataMigrator: info('Deleting models with ind_excluido...') for obj in self.to_delete: obj.delete() + info('Deleting unnecessary stubs...') + self.delete_stubs() def _do_migrate(self, obj): if isinstance(obj, AppConfig): @@ -245,6 +251,19 @@ class DataMigrator: if getattr(old, 'ind_excluido', False): self.to_delete.append(new) + def delete_stubs(self): + for line in stubs_list: + stub_id = line[0] + model = line[1] + related_model = line[2] + field_name = line[3] + + # Filter all objects in model and delete from related model + # if quantity is equal to zero + obj_quantity = model.objects.filter(**{field_name: stub_id}) + if obj_quantity.count() == 0: + related_model.objects.get(**{'id': stub_id}).delete() + def migrate(obj=appconfs): dm = DataMigrator()