Python django.db.migrations.Migration() Examples

The following are code examples for showing how to use django.db.migrations.Migration(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-move-model   Author: alexei   File: movemodel.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_model_fk_migrations(self, dependencies=[]):
        _migrations = []

        model_opts = self.to_state.apps.get_model(self.dest_app, self.model_name)._meta

        for field in model_opts.get_fields(include_hidden=True):
            if field.is_relation:
                operations = []
                operations.append(
                    migrations.AlterField(
                        model_name=field.related_model._meta.model_name,
                        name=field.remote_field.name,
                        field=field.remote_field,
                    )
                )
                migration = Migration('alter_model_fk', field.related_model._meta.app_label)
                migration.dependencies = dependencies
                migration.operations = operations

                _migrations.append(migration)

        return _migrations 
Example 2
Project: orchestra   Author: b12io   File: 0056_create_new_task_communication_type.py    Apache License 2.0 6 votes vote down vote up
def _add_communication_type(apps, schema_editor, communication_type):
    Worker = apps.get_model('orchestra', 'Worker')
    CommunicationPreference = apps.get_model('orchestra',
                                             'CommunicationPreference')
    for worker in Worker.objects.all():
        communication_preference, created = (
            CommunicationPreference.objects.get_or_create(
                worker=worker,
                communication_type=communication_type))

        # By default set both Slack and Email notifications to True
        if created:
            communication_preference.methods.slack = True
            communication_preference.methods.email = True
        communication_preference.save()
################# CommunicationType Migration Boilerplate Start ########## 
Example 3
Project: django-mysql   Author: adamchainz   File: test_operations.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def apply_operations(self, app_label, project_state, operations):
        migration = migrations.Migration("name", app_label)
        migration.operations = operations
        with connection.schema_editor() as editor:
            return migration.apply(project_state, editor) 
Example 4
Project: modoboa-imap-migration   Author: modoboa   File: 0003_auto_20190207_0919.py    ISC License 6 votes vote down vote up
def create_default_provider(apps, schema_editor):
    """Create default provider based on old settings."""
    EmailProvider = apps.get_model("modoboa_imap_migration", "EmailProvider")
    Migration = apps.get_model("modoboa_imap_migration", "Migration")
    LocalConfig = apps.get_model("core", "LocalConfig")
    lc = LocalConfig.objects.first()
    if not lc:
        return
    params = lc._parameters.get("modoboa_imap_migration")
    if params is None:
        return
    provider = EmailProvider.objects.create(
        name="Default",
        address=params["server_address"],
        port=params["server_port"],
        secured=params["secured"]
    )
    for migration in Migration.objects.select_related("mailbox__domain"):
        migration.provider = provider
        migration.username = (
            migration.mailbox.address + "@" + migration.mailbox.domain.name)
        migration.save(update_fields=["provider", "username"]) 
Example 5
Project: django-migration-linter   Author: 3YOURMIND   File: test_linter.py    Apache License 2.0 5 votes vote down vote up
def test_has_errors(self):
        linter = MigrationLinter(database="mysql")
        self.assertFalse(linter.has_errors)

        m = Migration("0001_create_table", "app_add_not_null_column")
        linter.lint_migration(m)
        self.assertFalse(linter.has_errors)

        m = Migration("0002_add_new_not_null_field", "app_add_not_null_column")
        linter.lint_migration(m)
        self.assertTrue(linter.has_errors)

        m = Migration("0001_create_table", "app_add_not_null_column")
        linter.lint_migration(m)
        self.assertTrue(linter.has_errors) 
Example 6
Project: django-migration-linter   Author: 3YOURMIND   File: test_linter.py    Apache License 2.0 5 votes vote down vote up
def test_exclude_migration_tests(self):
        m = Migration("0002_add_new_not_null_field", "app_add_not_null_column")

        linter = MigrationLinter(exclude_migration_tests=[], database="mysql")
        linter.lint_migration(m)
        self.assertTrue(linter.has_errors)

        linter = MigrationLinter(exclude_migration_tests=["NOT_NULL"], database="mysql")
        linter.lint_migration(m)
        self.assertFalse(linter.has_errors) 
Example 7
Project: django-move-model   Author: alexei   File: movemodel.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_rename_table_migration(self, dependencies=[]):
        database_operations = []
        state_operations = []

        database_operations.append(
            migrations.AlterModelTable(
                self.model_name.lower(),
                '{}_{}'.format(self.dest_app, self.model_name.lower())
            )
        )

        migration = Migration('rename_table', self.source_app)
        migration.dependencies = dependencies
        migration.operations = [
            migrations.SeparateDatabaseAndState(
                database_operations=database_operations,
                state_operations=state_operations
            )
        ]
        return migration 
Example 8
Project: ozp-backend   Author: aml-development   File: 0013_notification_fill_migrate.py    Apache License 2.0 5 votes vote down vote up
def forwards(apps, schema_editor):
    if not schema_editor.connection.alias == 'default':
        return
    interactive_migration()
    # Migration code goes here
    # notification_fill.run()
    # Running the script automatically was making any change in the profile raise in exception 
Example 9
Project: zulip   Author: zulip   File: 0074_fix_duplicate_attachments.py    Apache License 2.0 5 votes vote down vote up
def fix_duplicate_attachments(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
    """Migration 0041 had a bug, where if multiple messages referenced the
    same attachment, rather than creating a single attachment object
    for all of them, we would incorrectly create one for each message.
    This results in exceptions looking up the Attachment object
    corresponding to a file that was used in multiple messages that
    predate migration 0041.

    This migration fixes this by removing the duplicates, moving their
    messages onto a single canonical Attachment object (per path_id).
    """
    Attachment = apps.get_model('zerver', 'Attachment')
    # Loop through all groups of Attachment objects with the same `path_id`
    for group in Attachment.objects.values('path_id').annotate(Count('id')).order_by().filter(id__count__gt=1):
        # Sort by the minimum message ID, to find the first attachment
        attachments = sorted(list(Attachment.objects.filter(path_id=group['path_id']).order_by("id")),
                             key = lambda x: min(x.messages.all().values_list('id')[0]))
        surviving = attachments[0]
        to_cleanup = attachments[1:]
        for a in to_cleanup:
            # For each duplicate attachment, we transfer its messages
            # to the canonical attachment object for that path, and
            # then delete the original attachment.
            for msg in a.messages.all():
                surviving.messages.add(msg)
            surviving.is_realm_public = surviving.is_realm_public or a.is_realm_public
            surviving.save()
            a.delete() 
Example 10
Project: opencraft   Author: open-craft   File: 0114_introduce_base_playbook_name.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def rollback_base_playbook_name(apps, schema_editor):
    """
    On rollback, warn that all custom playbook names will be lost.
    The defaults, based on the openedx_release, can be recalculated using the
    function above when the migration is performed.
    """
    print('\nReverting this migration causes data loss...')
    print('All customized playbook_names set will be lost!')


# Migration ################################################################### 
Example 11
Project: scale   Author: ngageoint   File: 0017_populate_data_type_tags.py    Apache License 2.0 5 votes vote down vote up
def populate_data_type_tags(apps, schema_editor):
    # Go through all of the Ingest models and convert the data_type string into an array of tags
    
    update = 'UPDATE ingest SET data_type_tags = string_to_array(data_type,\',\') WHERE data_type <> \'\''
    with connection.cursor() as cursor:
        cursor.execute(update)
        count = cursor.rowcount
        if count:
            print('%d entries updated with data type tags' % count)

    print ('Migration finished.') 
Example 12
Project: scale   Author: ngageoint   File: 0032_recipe_type_link_tables.py    Apache License 2.0 5 votes vote down vote up
def populate_recipe_type_link_tables(apps, schema_editor):
    # Go through all of the recipe type models and create links for their sub recipes and job types
    JobType = apps.get_model('job', 'JobType')
    RecipeType = apps.get_model('recipe', 'RecipeType')

    total_count = RecipeType.objects.all().count()
    if not total_count:
        return

    print('\nCreating new recipe link table rows: %i' % total_count)
    recipe_types = RecipeType.objects.all()
    done_count = 0
    fail_count = 0
    for rt in recipe_types:
        try:
            create_recipe_type_job_links_from_definition(apps, rt)
            create_recipe_type_sub_links_from_definition(apps, rt)
        except (JobType.DoesNotExist, RecipeType.DoesNotExist) as ex:
            fail_count += 1
            print ('Failed creating links for recipe type %i: %s' % (rt.id, ex))

        done_count += 1
        percent = (float(done_count) / float(total_count)) * 100.00
        print('Progress: %i/%i (%.2f%%)' % (done_count, total_count, percent))

    print ('Migration finished. Failed: %i' % fail_count) 
Example 13
Project: scale   Author: ngageoint   File: 0016_populate_data_type_tags.py    Apache License 2.0 5 votes vote down vote up
def populate_data_type_tags(apps, schema_editor):
    # Go through all of the ScaleFile models and convert the data_type string into an array of tags
    update = 'UPDATE scale_file SET data_type_tags = string_to_array(data_type,\',\') WHERE data_type <> \'\''
    with connection.cursor() as cursor:
        cursor.execute(update)
        count = cursor.rowcount
        if count:
            print('%d entries updated with data type tags' % count)

    print ('Migration finished.') 
Example 14
Project: django-move-model   Author: alexei   File: movemodel.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _get_create_model_migration(self, dependencies=[]):
        database_operations = []
        state_operations = []

        model_state = self.to_state.models[self.dest_app, self.model_name.lower()]
        model_opts = self.to_state.apps.get_model(self.dest_app, self.model_name)._meta
        related_fields = {}
        for field in model_opts.local_fields:
            if field.remote_field:
                if field.remote_field.model:
                    if not field.remote_field.parent_link:
                        related_fields[field.name] = field
                if (getattr(field.remote_field, 'through', None) and
                        not field.remote_field.through._meta.auto_created):
                    related_fields[field.name] = field
        for field in model_opts.local_many_to_many:
            if field.remote_field.model:
                related_fields[field.name] = field
            if getattr(field.remote_field, 'through', None) and not field.remote_field.through._meta.auto_created:
                related_fields[field.name] = field

        state_operations.append(
            migrations.CreateModel(
                name=model_state.name,
                fields=[d for d in model_state.fields if d[0] not in related_fields],
                options=model_state.options,
                bases=model_state.bases,
                managers=model_state.managers,
            )
        )

        migration = Migration('create_model', self.dest_app)
        migration.dependencies = dependencies
        migration.operations = [
            migrations.SeparateDatabaseAndState(
                database_operations=database_operations,
                state_operations=state_operations,
            )
        ]
        return migration 
Example 15
Project: django-move-model   Author: alexei   File: movemodel.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _get_delete_model_migration(self, dependencies=[]):
        database_operations = []
        state_operations = []

        state_operations.append(migrations.DeleteModel(name=self.model_name))

        migration = Migration('delete_model', self.source_app)
        migration.dependencies = dependencies
        migration.operations = [
            migrations.SeparateDatabaseAndState(
                database_operations=database_operations,
                state_operations=state_operations,
            )
        ]
        return migration 
Example 16
Project: scale   Author: ngageoint   File: 0016_recipefile_data.py    Apache License 2.0 4 votes vote down vote up
def populate_recipe_file(apps, schema_editor):
        # Go through all of the recipe models and create a recipe file model for each of the recipe input files
        Recipe = apps.get_model('recipe', 'Recipe')
        RecipeFile = apps.get_model('recipe', 'RecipeFile')
        ScaleFile = apps.get_model('storage', 'ScaleFile')

        total_count = Recipe.objects.all().count()
        if not total_count:
            return

        print('\nCreating new recipe_file table rows: %i' % total_count)
        done_count = 0
        fail_count = 0
        batch_size = 500
        while done_count < total_count:
            batch_end = done_count + batch_size

            # Build a unique list of all valid input file ids
            batch_file_ids = set()
            recipes = Recipe.objects.all().order_by('id')[done_count:batch_end]
            for recipe in recipes:
                batch_file_ids.update(LegacyRecipeData(recipe.data).get_input_file_ids())
            valid_file_ids = {scale_file.id for scale_file in ScaleFile.objects.filter(pk__in=batch_file_ids)}

            # Create a model for each recipe input file
            recipe_files = []
            for recipe in recipes:
                input_file_ids = LegacyRecipeData(recipe.data).get_input_file_ids()
                for input_file_id in input_file_ids:
                    if input_file_id in valid_file_ids:
                        recipe_file = RecipeFile()
                        recipe_file.recipe_id = recipe.id
                        recipe_file.scale_file_id = input_file_id
                        recipe_file.created = recipe.created
                        recipe_files.append(recipe_file)
                    else:
                        fail_count += 1
                        print('Failed recipe: %i -> file: %i' % (recipe.id, input_file_id))

            RecipeFile.objects.bulk_create(recipe_files)

            done_count += len(recipes)
            percent = (float(done_count) / float(total_count)) * 100.00
            print('Progress: %i/%i (%.2f%%)' % (done_count, total_count, percent))
        print ('Migration finished. Failed: %i' % fail_count) 
Example 17
Project: wagtail-translation   Author: skirsdeda   File: 9999_wagtail_translation.py    MIT License 4 votes vote down vote up
def __init__(self, name, app_label):
        # by changing app_label here to 'wagtailcore' we trick Django migrations system
        # to think that this migration belongs to wagtailcore app
        # this is necessary to make model name resolution work
        app_label = 'wagtailcore'
        super(Migration, self).__init__(name, app_label)

        # find last wagtailcore migration
        mod_name  = MigrationLoader.migrations_module(app_label)
        if DJANGO_VERSION >= (1, 11):
            # Django 1.11 returns tuple(str, bool) while older versions return str
            mod_name = mod_name[0]
        mod = import_module(mod_name)
        migrations = []
        # this loop acts the same way as MigrationLoader.
        for name in os.listdir(os.path.dirname(mod.__file__)):
            if not name.endswith('.py'):
                continue
            import_name = name.rsplit('.', 1)[0]
            if import_name[0] in '_.~':
                continue
            migrations.append(import_name)
        last_migration = sorted(migrations, reverse=True)[0]
        # By using `replaces` we make sure that this migration doesn't have ambiguous `app_label`.
        # When this migration is applied Django writes only replaced migration
        # to django_migrations table in DB. Otherwise migration would have
        # 'wagtailtranslation' as app_label in django_migrations table and
        # `migrate` command would consider this migration as unapplied due
        # to app_label mismatch.
        self.replaces = [
            (app_label, last_migration),
        ]

        # import operations from wagtail migration we are replacing
        # and prepend them to operations of this migration
        mod_path = '{}.{}'.format(mod_name, last_migration)
        orig_migration = import_module(mod_path).Migration
        self.operations[:0] = orig_migration.operations
        self.dependencies = orig_migration.dependencies

    # Dynamically define AddField operations for all Page field translations.
    # This always uses current AVAILABLE_LANGUAGES setting.
    # In case languages are changed after running this migration, `makemigrations`
    # command would do nothing for Page model. One would have to run `sync_translation_fields`
    # command from modeltranslation to get DB schema in sync.