Python django.db.migrations.AlterField() Examples

The following are 30 code examples of django.db.migrations.AlterField(). 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 also want to check out all available functions/classes of the module django.db.migrations , or try the search function .
Example #1
Source File: 0002_pk_migration.py    From django-rest-passwordreset with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
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
Source File: test_hstore_autodetect.py    From django-postgres-extra with 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 #3
Source File: test_optimizer.py    From djongo with 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 #4
Source File: test_optimizer.py    From djongo with 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 #5
Source File: test_operations.py    From djongo with 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 #6
Source File: test_operations.py    From djongo with 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 #7
Source File: test_operations.py    From djongo with 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 #8
Source File: test_operations.py    From djongo with 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 #9
Source File: test_operations.py    From djongo with 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 #10
Source File: test_operations.py    From djongo with 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 #11
Source File: test_operations.py    From djongo with 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 #12
Source File: test_operations.py    From djongo with 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
Source File: test_operations.py    From djongo with 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 #14
Source File: test_optimizer.py    From djongo with 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 #15
Source File: test_operations.py    From djongo with 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 #16
Source File: test_optimizer.py    From djongo with 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 #17
Source File: test_operations.py    From django-sqlserver with 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 #18
Source File: test_operations.py    From django-sqlserver with 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 #19
Source File: test_operations.py    From djongo with 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 #20
Source File: test_operations.py    From django-sqlserver with 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 #21
Source File: test_hstore_autodetect.py    From django-postgres-extra with 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 #22
Source File: test_operations.py    From django-sqlserver with 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 #23
Source File: 0002_auto_20150507_1708.py    From django-andablog with 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 #24
Source File: test_optimizer.py    From django-sqlserver with 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 #25
Source File: test_operations.py    From djongo with 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 #26
Source File: test_operations.py    From djongo with 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 #27
Source File: test_optimizer.py    From django-sqlserver with 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 #28
Source File: 0011_user_id_to_uuid.py    From desec-stack with 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 #29
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_alter_field_reloads_state_on_fk_with_to_field_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_with_to_field_target_changes'
        project_state = self.apply_operations(app_label, ProjectState(), operations=[
            migrations.CreateModel('Rider', fields=[
                ('id', models.CharField(primary_key=True, max_length=100)),
                ('slug', models.CharField(unique=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, to_field='slug')),
                ('slug', models.CharField(unique=True, max_length=100)),
            ]),
            migrations.CreateModel('PonyRider', fields=[
                ('id', models.AutoField(primary_key=True)),
                ('pony', models.ForeignKey('%s.Pony' % app_label, models.CASCADE, to_field='slug')),
            ]),
        ])
        project_state = self.apply_operations(app_label, project_state, operations=[
            migrations.AlterField('Rider', 'slug', models.CharField(unique=True, max_length=99)),
            migrations.AlterField('Pony', 'slug', models.CharField(unique=True, max_length=99)),
        ]) 
Example #30
Source File: migrations.py    From django-postgres-extra with MIT License 5 votes vote down vote up
def alter_field(old_field, new_field, filters: List[str]):
    """Alters a field from one state to the other.

    Arguments:
        old_field:
            The field before altering it.

        new_field:
            The field after altering it.

        filters:
            List of strings to filter
            SQL statements on.
    """

    model = define_fake_model({"title": old_field})
    state = migrations.state.ProjectState.from_apps(apps)

    apply_migration(
        [
            migrations.CreateModel(
                model.__name__, fields=[("title", old_field.clone())]
            )
        ],
        state,
    )

    with filtered_schema_editor(*filters) as calls:
        apply_migration(
            [migrations.AlterField(model.__name__, "title", new_field)], state
        )

    yield calls