Python django.db.migrations.AlterField() Examples

The following are 30 code examples for showing how to use django.db.migrations.AlterField(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.migrations , or try the search function .

Example 1
def get_migrations_for_django_21_and_newer():
    return [
        # remove primary key information from 'key' field
        migrations.AlterField(
            model_name='resetpasswordtoken',
            name='key',
            field=models.CharField(db_index=True, primary_key=False, max_length=64, unique=True, verbose_name='Key'),
        ),
        # add a new id field
        migrations.AddField(
            model_name='resetpasswordtoken',
            name='id',
            field=models.AutoField(primary_key=True, serialize=False),
            preserve_default=False,
        ),
        migrations.RunPython(
            populate_auto_incrementing_pk_field,
            migrations.RunPython.noop
        ),
    ] 
Example 2
Project: django-andablog   Author: WimpyAnalytics   File: 0002_auto_20150507_1708.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_operations():
    """
    This will break things if you upgrade Django to 1.8 having already applied this migration in 1.7.
    Since this is for a demo site it doesn't really matter (simply blow away the DB if you want to go to 1.8)

    Our demo site is a unusual in that we want to run it's tests (for integration testing) in multiple Django versions.
    Typical sites don't have to worry about that sort of thing.
    """
    compatible = (1, 8) <= DJANGO_VERSION < (1, 10)
    if not compatible:
        return []

    return [
        migrations.AlterField(
            model_name='user',
            name='groups',
            field=models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups'),
        ),
        migrations.AlterField(
            model_name='user',
            name='last_login',
            field=models.DateTimeField(null=True, verbose_name='last login', blank=True),
        ),
    ] 
Example 3
Project: django-sqlserver   Author: denisenkom   File: test_optimizer.py    License: MIT License 6 votes vote down vote up
def test_alter_field_rename_field(self):
        """
        RenameField should optimize to the other side of AlterField,
        and into itself.
        """
        self.assertOptimizesTo(
            [
                migrations.AlterField("Foo", "name", models.CharField(max_length=255)),
                migrations.RenameField("Foo", "name", "title"),
                migrations.RenameField("Foo", "title", "nom"),
            ],
            [
                migrations.RenameField("Foo", "name", "nom"),
                migrations.AlterField("Foo", "nom", models.CharField(max_length=255)),
            ],
        ) 
Example 4
Project: django-sqlserver   Author: denisenkom   File: test_optimizer.py    License: MIT License 6 votes vote down vote up
def test_optimize_through_fields(self):
        """
        field-level through checking is working. This should manage to collapse
        model Foo to nonexistence, and model Bar to a single IntegerField
        called "width".
        """
        self.assertOptimizesTo(
            [
                migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
                migrations.CreateModel("Bar", [("size", models.IntegerField())]),
                migrations.AddField("Foo", "age", models.IntegerField()),
                migrations.AddField("Bar", "width", models.IntegerField()),
                migrations.AlterField("Foo", "age", models.IntegerField()),
                migrations.RenameField("Bar", "size", "dimensions"),
                migrations.RemoveField("Foo", "age"),
                migrations.RenameModel("Foo", "Phou"),
                migrations.RemoveField("Bar", "dimensions"),
                migrations.RenameModel("Phou", "Fou"),
                migrations.DeleteModel("Fou"),
            ],
            [
                migrations.CreateModel("Bar", [("width", models.IntegerField())]),
            ],
        ) 
Example 5
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 6 votes vote down vote up
def test_repoint_field_m2m(self):
        project_state = self.set_up_test_model("test_alflmm", second_model=True, third_model=True)

        project_state = self.apply_operations("test_alflmm", project_state, operations=[
            migrations.AddField("Pony", "places", models.ManyToManyField("Stable", related_name="ponies"))
        ])
        Pony = project_state.apps.get_model("test_alflmm", "Pony")

        project_state = self.apply_operations("test_alflmm", project_state, operations=[
            migrations.AlterField("Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"))
        ])

        # Ensure the new field actually works
        Pony = project_state.apps.get_model("test_alflmm", "Pony")
        p = Pony.objects.create(pink=False, weight=4.55)
        p.places.create()
        self.assertEqual(p.places.count(), 1)
        p.places.all().delete() 
Example 6
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 6 votes vote down vote up
def test_alter_field_pk(self):
        """
        Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
        """
        project_state = self.set_up_test_model("test_alflpk")
        # Test the state alteration
        operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflpk", new_state)
        self.assertIsInstance(project_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.AutoField)
        self.assertIsInstance(new_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.IntegerField)
        # Test the database alteration
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflpk", editor, project_state, new_state)
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflpk", editor, new_state, project_state) 
Example 7
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 6 votes vote down vote up
def test_alter_field_with_index(self):
        """
        Test AlterField operation with an index to ensure indexes created via
        Meta.indexes don't get dropped with sqlite3 remake.
        """
        project_state = self.set_up_test_model("test_alflin", index=True)
        operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflin", new_state)
        # Test the database alteration
        self.assertColumnNotNull("test_alflin_pony", "pink")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflin", editor, project_state, new_state)
        # Index hasn't been dropped
        self.assertIndexExists("test_alflin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflin", editor, new_state, project_state)
        # Ensure the index is still there
        self.assertIndexExists("test_alflin_pony", ["pink"]) 
Example 8
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 6 votes vote down vote up
def test_alter_fk_non_fk(self):
        """
        Altering an FK to a non-FK works (#23244)
        """
        # Test the state alteration
        operation = migrations.AlterField(
            model_name="Rider",
            name="pony",
            field=models.FloatField(),
        )
        project_state, new_state = self.make_test_state("test_afknfk", operation, related_model=True)
        # Test the database alteration
        self.assertColumnExists("test_afknfk_rider", "pony_id")
        self.assertColumnNotExists("test_afknfk_rider", "pony")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_afknfk", editor, project_state, new_state)
        self.assertColumnExists("test_afknfk_rider", "pony")
        self.assertColumnNotExists("test_afknfk_rider", "pony_id")
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_afknfk", editor, new_state, project_state)
        self.assertColumnExists("test_afknfk_rider", "pony_id")
        self.assertColumnNotExists("test_afknfk_rider", "pony") 
Example 9
Project: djongo   Author: nesdis   File: test_optimizer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_rename_field(self):
        """
        RenameField should optimize to the other side of AlterField,
        and into itself.
        """
        self.assertOptimizesTo(
            [
                migrations.AlterField("Foo", "name", models.CharField(max_length=255)),
                migrations.RenameField("Foo", "name", "title"),
                migrations.RenameField("Foo", "title", "nom"),
            ],
            [
                migrations.RenameField("Foo", "name", "nom"),
                migrations.AlterField("Foo", "nom", models.CharField(max_length=255)),
            ],
        ) 
Example 10
Project: djongo   Author: nesdis   File: test_optimizer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_optimize_through_fields(self):
        """
        field-level through checking is working. This should manage to collapse
        model Foo to nonexistence, and model Bar to a single IntegerField
        called "width".
        """
        self.assertOptimizesTo(
            [
                migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
                migrations.CreateModel("Bar", [("size", models.IntegerField())]),
                migrations.AddField("Foo", "age", models.IntegerField()),
                migrations.AddField("Bar", "width", models.IntegerField()),
                migrations.AlterField("Foo", "age", models.IntegerField()),
                migrations.RenameField("Bar", "size", "dimensions"),
                migrations.RemoveField("Foo", "age"),
                migrations.RenameModel("Foo", "Phou"),
                migrations.RemoveField("Bar", "dimensions"),
                migrations.RenameModel("Phou", "Fou"),
                migrations.DeleteModel("Fou"),
            ],
            [
                migrations.CreateModel("Bar", [("width", models.IntegerField())]),
            ],
        ) 
Example 11
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_repoint_field_m2m(self):
        project_state = self.set_up_test_model("test_alflmm", second_model=True, third_model=True)

        project_state = self.apply_operations("test_alflmm", project_state, operations=[
            migrations.AddField("Pony", "places", models.ManyToManyField("Stable", related_name="ponies"))
        ])
        Pony = project_state.apps.get_model("test_alflmm", "Pony")

        project_state = self.apply_operations("test_alflmm", project_state, operations=[
            migrations.AlterField("Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"))
        ])

        # Ensure the new field actually works
        Pony = project_state.apps.get_model("test_alflmm", "Pony")
        p = Pony.objects.create(pink=False, weight=4.55)
        p.places.create()
        self.assertEqual(p.places.count(), 1)
        p.places.all().delete() 
Example 12
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_pk(self):
        """
        Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
        """
        project_state = self.set_up_test_model("test_alflpk")
        # Test the state alteration
        operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflpk", new_state)
        self.assertIsInstance(project_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.AutoField)
        self.assertIsInstance(new_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.IntegerField)
        # Test the database alteration
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflpk", editor, project_state, new_state)
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflpk", editor, new_state, project_state) 
Example 13
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_reloads_state_on_fk_target_changes(self):
        """
        If AlterField doesn't reload state appropriately, the second AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_alter_field_reloads_state_on_fk_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'id', models.CharField(primary_key=True, max_length=99)),
            migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
        ]) 
Example 14
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rename_field_reloads_state_on_fk_target_changes(self):
        """
        If RenameField doesn't reload state appropriately, the AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_rename_field_reloads_state_on_fk_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.RenameField('Rider', 'id', 'id2'),
            migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
        ], atomic=connection.features.supports_atomic_references_rename) 
Example 15
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_with_index(self):
        """
        Test AlterField operation with an index to ensure indexes created via
        Meta.indexes don't get dropped with sqlite3 remake.
        """
        project_state = self.set_up_test_model("test_alflin", index=True)
        operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflin", new_state)
        # Test the database alteration
        self.assertColumnNotNull("test_alflin_pony", "pink")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflin", editor, project_state, new_state)
        # Index hasn't been dropped
        self.assertIndexExists("test_alflin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflin", editor, new_state, project_state)
        # Ensure the index is still there
        self.assertIndexExists("test_alflin_pony", ["pink"]) 
Example 16
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_fk_non_fk(self):
        """
        Altering an FK to a non-FK works (#23244)
        """
        # Test the state alteration
        operation = migrations.AlterField(
            model_name="Rider",
            name="pony",
            field=models.FloatField(),
        )
        project_state, new_state = self.make_test_state("test_afknfk", operation, related_model=True)
        # Test the database alteration
        self.assertColumnExists("test_afknfk_rider", "pony_id")
        self.assertColumnNotExists("test_afknfk_rider", "pony")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_afknfk", editor, project_state, new_state)
        self.assertColumnExists("test_afknfk_rider", "pony")
        self.assertColumnNotExists("test_afknfk_rider", "pony_id")
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_afknfk", editor, new_state, project_state)
        self.assertColumnExists("test_afknfk_rider", "pony_id")
        self.assertColumnNotExists("test_afknfk_rider", "pony") 
Example 17
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_geom_field_dim(self):
        Neighborhood = self.current_state.apps.get_model('gis', 'Neighborhood')
        p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
        Neighborhood.objects.create(name='TestDim', geom=MultiPolygon(p1, p1))
        # Add 3rd dimension.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 3}
        )
        self.assertTrue(Neighborhood.objects.first().geom.hasz)
        # Rewind to 2 dimensions.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 2}
        )
        self.assertFalse(Neighborhood.objects.first().geom.hasz) 
Example 18
Project: djongo   Author: nesdis   File: test_optimizer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_rename_field(self):
        """
        RenameField should optimize to the other side of AlterField,
        and into itself.
        """
        self.assertOptimizesTo(
            [
                migrations.AlterField("Foo", "name", models.CharField(max_length=255)),
                migrations.RenameField("Foo", "name", "title"),
                migrations.RenameField("Foo", "title", "nom"),
            ],
            [
                migrations.RenameField("Foo", "name", "nom"),
                migrations.AlterField("Foo", "nom", models.CharField(max_length=255)),
            ],
        ) 
Example 19
Project: djongo   Author: nesdis   File: test_optimizer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_optimize_through_fields(self):
        """
        field-level through checking is working. This should manage to collapse
        model Foo to nonexistence, and model Bar to a single IntegerField
        called "width".
        """
        self.assertOptimizesTo(
            [
                migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
                migrations.CreateModel("Bar", [("size", models.IntegerField())]),
                migrations.AddField("Foo", "age", models.IntegerField()),
                migrations.AddField("Bar", "width", models.IntegerField()),
                migrations.AlterField("Foo", "age", models.IntegerField()),
                migrations.RenameField("Bar", "size", "dimensions"),
                migrations.RemoveField("Foo", "age"),
                migrations.RenameModel("Foo", "Phou"),
                migrations.RemoveField("Bar", "dimensions"),
                migrations.RenameModel("Phou", "Fou"),
                migrations.DeleteModel("Fou"),
            ],
            [
                migrations.CreateModel("Bar", [("width", models.IntegerField())]),
            ],
        ) 
Example 20
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_m2m(self):
        project_state = self.set_up_test_model("test_alflmm", second_model=True)

        project_state = self.apply_operations("test_alflmm", project_state, operations=[
            migrations.AddField("Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"))
        ])
        Pony = project_state.apps.get_model("test_alflmm", "Pony")
        self.assertFalse(Pony._meta.get_field('stables').blank)

        project_state = self.apply_operations("test_alflmm", project_state, operations=[
            migrations.AlterField(
                "Pony", "stables", models.ManyToManyField(to="Stable", related_name="ponies", blank=True)
            )
        ])
        Pony = project_state.apps.get_model("test_alflmm", "Pony")
        self.assertTrue(Pony._meta.get_field('stables').blank) 
Example 21
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_pk(self):
        """
        Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
        """
        project_state = self.set_up_test_model("test_alflpk")
        # Test the state alteration
        operation = migrations.AlterField("Pony", "id", models.IntegerField(primary_key=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflpk", new_state)
        self.assertIsInstance(project_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.AutoField)
        self.assertIsInstance(new_state.models["test_alflpk", "pony"].get_field_by_name("id"), models.IntegerField)
        # Test the database alteration
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflpk", editor, project_state, new_state)
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflpk", editor, new_state, project_state) 
Example 22
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_reloads_state_on_fk_target_changes(self):
        """
        If AlterField doesn't reload state appropriately, the second AlterField
        crashes on MySQL due to not dropping the PonyRider.pony foreign key
        constraint before modifying the column.
        """
        app_label = 'alter_alter_field_reloads_state_on_fk_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
            ]),
            migrations.CreateModel('Pony', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('rider', models.ForeignKey('%s.Rider' % app_label, models.CASCADE)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE)),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'id', models.CharField(primary_key=True, max_length=99)),
            migrations.AlterField('Pony', 'id', models.CharField(primary_key=True, max_length=99)),
        ]) 
Example 23
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_with_index(self):
        """
        Test AlterField operation with an index to ensure indexes created via
        Meta.indexes don't get dropped with sqlite3 remake.
        """
        project_state = self.set_up_test_model("test_alflin", index=True)
        operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflin", new_state)
        # Test the database alteration
        self.assertColumnNotNull("test_alflin_pony", "pink")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflin", editor, project_state, new_state)
        # Index hasn't been dropped
        self.assertIndexExists("test_alflin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflin", editor, new_state, project_state)
        # Ensure the index is still there
        self.assertIndexExists("test_alflin_pony", ["pink"]) 
Example 24
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_fk_non_fk(self):
        """
        Altering an FK to a non-FK works (#23244)
        """
        # Test the state alteration
        operation = migrations.AlterField(
            model_name="Rider",
            name="pony",
            field=models.FloatField(),
        )
        project_state, new_state = self.make_test_state("test_afknfk", operation, related_model=True)
        # Test the database alteration
        self.assertColumnExists("test_afknfk_rider", "pony_id")
        self.assertColumnNotExists("test_afknfk_rider", "pony")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_afknfk", editor, project_state, new_state)
        self.assertColumnExists("test_afknfk_rider", "pony")
        self.assertColumnNotExists("test_afknfk_rider", "pony_id")
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_afknfk", editor, new_state, project_state)
        self.assertColumnExists("test_afknfk_rider", "pony_id")
        self.assertColumnNotExists("test_afknfk_rider", "pony") 
Example 25
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_geom_field_dim(self):
        Neighborhood = self.current_state.apps.get_model('gis', 'Neighborhood')
        p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
        Neighborhood.objects.create(name='TestDim', geom=MultiPolygon(p1, p1))
        # Add 3rd dimension.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 3}
        )
        self.assertTrue(Neighborhood.objects.first().geom.hasz)
        # Rewind to 2 dimensions.
        self.alter_gis_model(
            migrations.AlterField, 'Neighborhood', 'geom', False,
            fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 2}
        )
        self.assertFalse(Neighborhood.objects.first().geom.hasz) 
Example 26
Project: django-postgres-extra   Author: SectorLabs   File: test_hstore_autodetect.py    License: MIT License 6 votes vote down vote up
def test_hstore_autodetect_uniqueness():
    """Tests whether changes in the `uniqueness` option are properly detected
    by the auto detector."""

    before = [
        migrations.state.ModelState(
            "tests", "Model1", [("title", HStoreField())]
        )
    ]
    after = [
        migrations.state.ModelState(
            "tests", "Model1", [("title", HStoreField(uniqueness=["en"]))]
        )
    ]

    changes = _detect_changes(before, after)

    _assert_autodetector(
        changes,
        [
            migrations.AlterField(
                "Model1", "title", HStoreField(uniqueness=["en"])
            )
        ],
    ) 
Example 27
Project: django-postgres-extra   Author: SectorLabs   File: test_hstore_autodetect.py    License: MIT License 6 votes vote down vote up
def test_hstore_autodetect_required():
    """Tests whether changes in the `required` option are properly detected by
    the auto detector."""

    before = [
        migrations.state.ModelState(
            "tests", "Model1", [("title", HStoreField())]
        )
    ]
    after = [
        migrations.state.ModelState(
            "tests", "Model1", [("title", HStoreField(required=["en"]))]
        )
    ]

    changes = _detect_changes(before, after)

    _assert_autodetector(
        changes,
        [
            migrations.AlterField(
                "Model1", "title", HStoreField(required=["en"])
            )
        ],
    ) 
Example 28
Project: GTDWeb   Author: lanbing510   File: optimizer.py    License: GNU General Public License v2.0 5 votes vote down vote up
def reduce_alter_field_rename_field(self, operation, other, in_between):
        if (operation.model_name_lower == other.model_name_lower and
                operation.name_lower == other.old_name_lower):
            return [
                other,
                migrations.AlterField(
                    model_name=operation.model_name,
                    name=other.new_name,
                    field=operation.field,
                ),
            ] 
Example 29
Project: desec-stack   Author: desec-io   File: 0011_user_id_to_uuid.py    License: MIT License 5 votes vote down vote up
def migrate_data(apps, schema_editor):
    # SQLite does not support altering constraints. However, we use it for tests only, and there's no data to migrate.
    if schema_editor.connection.vendor == 'sqlite':
        return

    def _sql_add_cascading_user_constraint(model_name, field_name):
        return f'ALTER TABLE desecapi_{model_name}' \
               f' ADD CONSTRAINT desecapi_{model_name}_{field_name}_id_update_cascade' \
               f' FOREIGN KEY (`{field_name}_id`) REFERENCES `desecapi_user` (`id`) ON UPDATE CASCADE'

    def _sql_drop_cascading_user_constraint(model_name, field_name):
        return f'ALTER TABLE desecapi_{model_name} DROP CONSTRAINT desecapi_{model_name}_{field_name}_id_update_cascade'

    # Add cascading foreign key constraints.
    # This has to be done after removing the regular constraints using migrations.AlterField. If done the other
    # way around, AlterField will drop the cascading constraint.
    schema_editor.execute(_sql_add_cascading_user_constraint('domain', 'owner')),
    schema_editor.execute(_sql_add_cascading_user_constraint('token', 'user')),

    # Repopulate user ID fields
    User = apps.get_model('desecapi', 'User')
    with transaction.atomic():
        for user in User.objects.all():
            User.objects.filter(email=user.email).update(id=uuid.uuid4().hex)

    # Remove cascading foreign key constraints
    schema_editor.execute(_sql_drop_cascading_user_constraint('domain', 'owner')),
    schema_editor.execute(_sql_drop_cascading_user_constraint('token', 'user')), 
Example 30
def get_migrations_for_django_before_21():
    return [
        # add a new id field (without primary key information)
        migrations.AddField(
            model_name='resetpasswordtoken',
            name='id',
            field=models.IntegerField(null=True),
            preserve_default=True,
        ),
        # fill the new pk field
        migrations.RunPython(
            populate_auto_incrementing_pk_field,
            migrations.RunPython.noop
        ),
        # add primary key information to id field
        migrations.AlterField(
            model_name='resetpasswordtoken',
            name='id',
            field=models.AutoField(primary_key=True, serialize=False)
        ),
        # remove primary key information from 'key' field
        migrations.AlterField(
            model_name='resetpasswordtoken',
            name='key',
            field=models.CharField(db_index=True, max_length=64, unique=True, verbose_name='Key'),
        ),
    ]