From 3578b9ffbf11bec35ad079df896a56e3a4b7b3e5 Mon Sep 17 00:00:00 2001 From: Luciano Almeida Date: Mon, 21 Mar 2016 15:06:48 -0300 Subject: [PATCH] Cria stub para PK igual a zero Signed-off-by: Luciano Almeida --- legacy/migration.py | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/legacy/migration.py b/legacy/migration.py index 5e8cf3ed6..31bfc1576 100644 --- a/legacy/migration.py +++ b/legacy/migration.py @@ -26,7 +26,7 @@ appconfs = [apps.get_app_config(n) for n in [ 'protocoloadm', ]] stubs_list = [] - +stub_created = False name_sets = [set(m.__name__ for m in ac.get_models()) for ac in appconfs] # apps do not overlap @@ -91,6 +91,9 @@ def warn(msg): def get_fk_related(field, value, label=None): + has_textfield = False + fields_dict = {} + global stub_created if value is not None: try: value = field.related_model.objects.get(id=value) @@ -100,9 +103,28 @@ def get_fk_related(field, value, label=None): field.name, value, field.model.__name__, label or '---') if value == 0: - # we interpret FK == 0 as actually FK == NONE - value = None - warn(msg + ' => using NONE for zero value') + # se FK == 0, criamos um stub e colocamos o valor DESCONHECIDO + # para qualquer TextField que possa haver + all_fields = field.related_model._meta.get_fields() + for related_field in all_fields: + if related_field.get_internal_type() == 'TextField': + fields_dict[related_field.name] = 'DESCONHECIDO' + has_textfield = True + elif related_field.get_internal_type() == 'CharField': + fields_dict[related_field.name] = 'DESC' + has_textfield = True + if has_textfield and field.null is False: + if not stub_created: + stub_created = mommy.make(field.related_model, + **fields_dict) + warn(msg + ' => STUB CREATED FOR NOT NULL FIELD') + value = stub_created + else: + value = stub_created + warn(msg + ' => USING STUB ALREADY CREATED') + else: + value = None + warn(msg + ' => using NONE for zero value') else: value = make_stub(field.related_model, value) stubs_list.append((value.id, field)) @@ -163,7 +185,6 @@ class DataMigrator: for field in new._meta.fields: old_field_name = renames.get(field.name) field_type = field.get_internal_type() - if old_field_name: old_value = getattr(old, old_field_name) if isinstance(field, models.ForeignKey): @@ -219,6 +240,7 @@ class DataMigrator: legacy_model_name = self.model_renames.get(model, model.__name__) legacy_model = legacy_app.get_model(legacy_model_name) legacy_pk_name = legacy_model._meta.pk.name + global stub_created # Clear all model entries # They may have been created in a previous migration attempt @@ -229,12 +251,14 @@ class DataMigrator: # There is no pk in the legacy table def save(new, old): new.save() + stub_created = False old_records = iter_sql_records( 'select * from ' + legacy_model._meta.db_table, 'legacy') else: def save(new, old): save_with_id(new, getattr(old, legacy_pk_name)) + stub_created = False old_records = legacy_model.objects.all().order_by(legacy_pk_name)