Python django.db.migrations.state.ModelState() Examples

The following are 30 code examples of django.db.migrations.state.ModelState(). 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.state , or try the search function .
Example #1
Source File: test_autodetector.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_create_model_with_indexes(self):
        """Test creation of new model with indexes already defined."""
        author = ModelState('otherapp', 'Author', [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
        ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]})
        changes = self.get_changes([], [author])
        added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx')
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 2)
        # Right actions order?
        self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) 
Example #2
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_rename_model_state_forwards(self):
        """
        RenameModel operations shouldn't trigger the caching of rendered apps
        on state without prior apps.
        """
        state = ProjectState()
        state.add_model(ModelState('migrations', 'Foo', []))
        operation = migrations.RenameModel('Foo', 'Bar')
        operation.state_forwards('migrations', state)
        self.assertNotIn('apps', state.__dict__)
        self.assertNotIn(('migrations', 'foo'), state.models)
        self.assertIn(('migrations', 'bar'), state.models)
        # Now with apps cached.
        apps = state.apps
        operation = migrations.RenameModel('Bar', 'Foo')
        operation.state_forwards('migrations', state)
        self.assertIs(state.apps, apps)
        self.assertNotIn(('migrations', 'bar'), state.models)
        self.assertIn(('migrations', 'foo'), state.models) 
Example #3
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_identical_regex_doesnt_alter(self):
        from_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[
                RegexValidator(
                    re.compile('^[-a-zA-Z0-9_]+\\Z'),
                    "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.",
                    'invalid'
                )
            ]))]
        )
        to_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))]
        )
        changes = self.get_changes([from_state], [to_state])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, "testapp", 0) 
Example #4
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_different_regex_does_alter(self):
        from_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[
                RegexValidator(
                    re.compile('^[a-z]+\\Z', 32),
                    "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.",
                    'invalid'
                )
            ]))]
        )
        to_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))]
        )
        changes = self.get_changes([from_state], [to_state])
        self.assertNumberMigrations(changes, "testapp", 1)
        self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) 
Example #5
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_create_model_with_indexes(self):
        """Test creation of new model with indexes already defined."""
        author = ModelState('otherapp', 'Author', [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
        ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]})
        changes = self.get_changes([], [author])
        added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx')
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 2)
        # Right actions order?
        self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) 
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_rename_model_state_forwards(self):
        """
        RenameModel operations shouldn't trigger the caching of rendered apps
        on state without prior apps.
        """
        state = ProjectState()
        state.add_model(ModelState('migrations', 'Foo', []))
        operation = migrations.RenameModel('Foo', 'Bar')
        operation.state_forwards('migrations', state)
        self.assertNotIn('apps', state.__dict__)
        self.assertNotIn(('migrations', 'foo'), state.models)
        self.assertIn(('migrations', 'bar'), state.models)
        # Now with apps cached.
        apps = state.apps
        operation = migrations.RenameModel('Bar', 'Foo')
        operation.state_forwards('migrations', state)
        self.assertIs(state.apps, apps)
        self.assertNotIn(('migrations', 'bar'), state.models)
        self.assertIn(('migrations', 'foo'), state.models) 
Example #7
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_identical_regex_doesnt_alter(self):
        from_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[
                RegexValidator(
                    re.compile('^[-a-zA-Z0-9_]+\\Z'),
                    "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.",
                    'invalid'
                )
            ]))]
        )
        to_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))]
        )
        changes = self.get_changes([from_state], [to_state])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, "testapp", 0) 
Example #8
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_different_regex_does_alter(self):
        from_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[
                RegexValidator(
                    re.compile('^[a-z]+\\Z', 32),
                    "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.",
                    'invalid'
                )
            ]))]
        )
        to_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))]
        )
        changes = self.get_changes([from_state], [to_state])
        self.assertNumberMigrations(changes, "testapp", 1)
        self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) 
Example #9
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_create_model_with_indexes(self):
        """Test creation of new model with indexes already defined."""
        author = ModelState('otherapp', 'Author', [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
        ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]})
        changes = self.get_changes([], [author])
        added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx')
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 2)
        # Right actions order?
        self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) 
Example #10
Source File: test_autodetector.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_multiple_bases(self):
        """#23956 - Inheriting models doesn't move *_ptr fields into AddField operations."""
        A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))])
        B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))])
        C = ModelState("app", "C", [], bases=("app.A", "app.B"))
        D = ModelState("app", "D", [], bases=("app.A", "app.B"))
        E = ModelState("app", "E", [], bases=("app.A", "app.B"))
        changes = self.get_changes([], [A, B, C, D, E])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, "app", 1)
        self.assertOperationTypes(changes, "app", 0, [
            "CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel"
        ])
        self.assertOperationAttributes(changes, "app", 0, 0, name="A")
        self.assertOperationAttributes(changes, "app", 0, 1, name="B")
        self.assertOperationAttributes(changes, "app", 0, 2, name="C")
        self.assertOperationAttributes(changes, "app", 0, 3, name="D")
        self.assertOperationAttributes(changes, "app", 0, 4, name="E") 
Example #11
Source File: test_autodetector.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_deconstruct_type(self):
        """
        #22951 -- Uninstantiated classes with deconstruct are correctly returned
        by deep_deconstruct during serialization.
        """
        author = ModelState(
            "testapp",
            "Author",
            [
                ("id", models.AutoField(primary_key=True)),
                ("name", models.CharField(
                    max_length=200,
                    # IntegerField intentionally not instantiated.
                    default=models.IntegerField,
                ))
            ],
        )
        changes = self.get_changes([], [author])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'testapp', 1)
        self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) 
Example #12
Source File: test_autodetector.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_create_model_and_unique_together(self):
        author = ModelState("otherapp", "Author", [
            ("id", models.AutoField(primary_key=True)),
            ("name", models.CharField(max_length=200)),
        ])
        book_with_author = ModelState("otherapp", "Book", [
            ("id", models.AutoField(primary_key=True)),
            ("author", models.ForeignKey("otherapp.Author", models.CASCADE)),
            ("title", models.CharField(max_length=200)),
        ], {
            "index_together": {("title", "author")},
            "unique_together": {("title", "author")},
        })
        changes = self.get_changes([self.book_with_no_author], [author, book_with_author])
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 4)
        # Right actions order?
        self.assertOperationTypes(
            changes, 'otherapp', 0,
            ['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether']
        ) 
Example #13
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_create_model_with_check_constraint(self):
        """Test creation of new model with constraints already defined."""
        author = ModelState('otherapp', 'Author', [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
        ], {'constraints': [models.CheckConstraint(check=models.Q(name__contains='Bob'), name='name_contains_bob')]})
        changes = self.get_changes([], [author])
        added_constraint = models.CheckConstraint(check=models.Q(name__contains='Bob'), name='name_contains_bob')
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 2)
        # Right actions order?
        self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddConstraint'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', constraint=added_constraint) 
Example #14
Source File: test_autodetector.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_identical_regex_doesnt_alter(self):
        from_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[
                RegexValidator(
                    re.compile('^[-a-zA-Z0-9_]+\\Z'),
                    "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.",
                    'invalid'
                )
            ]))]
        )
        to_state = ModelState(
            "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))]
        )
        changes = self.get_changes([from_state], [to_state])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, "testapp", 0) 
Example #15
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_deconstruct_type(self):
        """
        #22951 -- Uninstantiated classes with deconstruct are correctly returned
        by deep_deconstruct during serialization.
        """
        author = ModelState(
            "testapp",
            "Author",
            [
                ("id", models.AutoField(primary_key=True)),
                ("name", models.CharField(
                    max_length=200,
                    # IntegerField intentionally not instantiated.
                    default=models.IntegerField,
                ))
            ],
        )
        changes = self.get_changes([], [author])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'testapp', 1)
        self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) 
Example #16
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_default_related_name_option(self):
        model_state = ModelState('app', 'model', [
            ('id', models.AutoField(primary_key=True)),
        ], options={'default_related_name': 'related_name'})
        changes = self.get_changes([], [model_state])
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['CreateModel'])
        self.assertOperationAttributes(
            changes, 'app', 0, 0, name='model',
            options={'default_related_name': 'related_name'},
        )
        altered_model_state = ModelState('app', 'Model', [
            ('id', models.AutoField(primary_key=True)),
        ])
        changes = self.get_changes([model_state], [altered_model_state])
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['AlterModelOptions'])
        self.assertOperationAttributes(changes, 'app', 0, 0, name='model', options={}) 
Example #17
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiple_bases(self):
        """#23956 - Inheriting models doesn't move *_ptr fields into AddField operations."""
        A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))])
        B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))])
        C = ModelState("app", "C", [], bases=("app.A", "app.B"))
        D = ModelState("app", "D", [], bases=("app.A", "app.B"))
        E = ModelState("app", "E", [], bases=("app.A", "app.B"))
        changes = self.get_changes([], [A, B, C, D, E])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, "app", 1)
        self.assertOperationTypes(changes, "app", 0, [
            "CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel"
        ])
        self.assertOperationAttributes(changes, "app", 0, 0, name="A")
        self.assertOperationAttributes(changes, "app", 0, 1, name="B")
        self.assertOperationAttributes(changes, "app", 0, 2, name="C")
        self.assertOperationAttributes(changes, "app", 0, 3, name="D")
        self.assertOperationAttributes(changes, "app", 0, 4, name="E") 
Example #18
Source File: test_operations.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_rename_model_state_forwards(self):
        """
        RenameModel operations shouldn't trigger the caching of rendered apps
        on state without prior apps.
        """
        state = ProjectState()
        state.add_model(ModelState('migrations', 'Foo', []))
        operation = migrations.RenameModel('Foo', 'Bar')
        operation.state_forwards('migrations', state)
        self.assertNotIn('apps', state.__dict__)
        self.assertNotIn(('migrations', 'foo'), state.models)
        self.assertIn(('migrations', 'bar'), state.models)
        # Now with apps cached.
        apps = state.apps
        operation = migrations.RenameModel('Bar', 'Foo')
        operation.state_forwards('migrations', state)
        self.assertIs(state.apps, apps)
        self.assertNotIn(('migrations', 'bar'), state.models)
        self.assertIn(('migrations', 'foo'), state.models) 
Example #19
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_create_model_and_unique_together(self):
        author = ModelState("otherapp", "Author", [
            ("id", models.AutoField(primary_key=True)),
            ("name", models.CharField(max_length=200)),
        ])
        book_with_author = ModelState("otherapp", "Book", [
            ("id", models.AutoField(primary_key=True)),
            ("author", models.ForeignKey("otherapp.Author", models.CASCADE)),
            ("title", models.CharField(max_length=200)),
        ], {
            "index_together": {("title", "author")},
            "unique_together": {("title", "author")},
        })
        changes = self.get_changes([self.book_with_no_author], [author, book_with_author])
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 4)
        # Right actions order?
        self.assertOperationTypes(
            changes, 'otherapp', 0,
            ['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether']
        ) 
Example #20
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_deconstruct_type(self):
        """
        #22951 -- Uninstantiated classes with deconstruct are correctly returned
        by deep_deconstruct during serialization.
        """
        author = ModelState(
            "testapp",
            "Author",
            [
                ("id", models.AutoField(primary_key=True)),
                ("name", models.CharField(
                    max_length=200,
                    # IntegerField intentionally not instantiated.
                    default=models.IntegerField,
                ))
            ],
        )
        changes = self.get_changes([], [author])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'testapp', 1)
        self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) 
Example #21
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_default_related_name_option(self):
        model_state = ModelState('app', 'model', [
            ('id', models.AutoField(primary_key=True)),
        ], options={'default_related_name': 'related_name'})
        changes = self.get_changes([], [model_state])
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['CreateModel'])
        self.assertOperationAttributes(
            changes, 'app', 0, 0, name='model',
            options={'default_related_name': 'related_name'},
        )
        altered_model_state = ModelState('app', 'Model', [
            ('id', models.AutoField(primary_key=True)),
        ])
        changes = self.get_changes([model_state], [altered_model_state])
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['AlterModelOptions'])
        self.assertOperationAttributes(changes, 'app', 0, 0, name='model', options={}) 
Example #22
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_multiple_bases(self):
        """#23956 - Inheriting models doesn't move *_ptr fields into AddField operations."""
        A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))])
        B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))])
        C = ModelState("app", "C", [], bases=("app.A", "app.B"))
        D = ModelState("app", "D", [], bases=("app.A", "app.B"))
        E = ModelState("app", "E", [], bases=("app.A", "app.B"))
        changes = self.get_changes([], [A, B, C, D, E])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, "app", 1)
        self.assertOperationTypes(changes, "app", 0, [
            "CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel"
        ])
        self.assertOperationAttributes(changes, "app", 0, 0, name="A")
        self.assertOperationAttributes(changes, "app", 0, 1, name="B")
        self.assertOperationAttributes(changes, "app", 0, 2, name="C")
        self.assertOperationAttributes(changes, "app", 0, 3, name="D")
        self.assertOperationAttributes(changes, "app", 0, 4, name="E") 
Example #23
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_circular_dependency_swappable2(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models but with the swappable not being the first migrated
        model.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            address = ModelState("a", "Address", [
                ("id", models.AutoField(primary_key=True)),
                ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)),
            ])
            tenant = ModelState("b", "Tenant", [
                ("id", models.AutoField(primary_key=True)),
                ("primary_address", models.ForeignKey("a.Address", models.CASCADE))],
                bases=(AbstractBaseUser,)
            )
            changes = self.get_changes([], [address, tenant])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 2)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertOperationTypes(changes, 'a', 1, ["AddField"])
        self.assertMigrationDependencies(changes, 'a', 0, [])
        self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'b', 1)
        self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) 
Example #24
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_circular_dependency_swappable_self(self):
        """
        #23322 - The dependency resolver knows to explicitly resolve
        swappable models.
        """
        with isolate_lru_cache(apps.get_swappable_settings_name):
            person = ModelState("a", "Person", [
                ("id", models.AutoField(primary_key=True)),
                ("parent1", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='children'))
            ])
            changes = self.get_changes([], [person])
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'a', 1)
        self.assertOperationTypes(changes, 'a', 0, ["CreateModel"])
        self.assertMigrationDependencies(changes, 'a', 0, []) 
Example #25
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_mti_inheritance_model_removal(self):
        Animal = ModelState('app', 'Animal', [
            ("id", models.AutoField(primary_key=True)),
        ])
        Dog = ModelState('app', 'Dog', [], bases=('app.Animal',))
        changes = self.get_changes([Animal, Dog], [Animal])
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['DeleteModel'])
        self.assertOperationAttributes(changes, 'app', 0, 0, name='Dog') 
Example #26
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_missing_field(self):
        state = ProjectState()
        state.add_model(ModelState('app', 'model', []))
        with self.assertRaisesMessage(FieldDoesNotExist, "app.model has no field named 'field'"):
            migrations.RenameField('model', 'field', 'new_field').state_forwards('app', state) 
Example #27
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_field_foreign_key_to_field(self):
        before = [
            ModelState('app', 'Foo', [
                ('id', models.AutoField(primary_key=True)),
                ('field', models.IntegerField(unique=True)),
            ]),
            ModelState('app', 'Bar', [
                ('id', models.AutoField(primary_key=True)),
                ('foo', models.ForeignKey('app.Foo', models.CASCADE, to_field='field')),
            ]),
        ]
        after = [
            ModelState('app', 'Foo', [
                ('id', models.AutoField(primary_key=True)),
                ('renamed_field', models.IntegerField(unique=True)),
            ]),
            ModelState('app', 'Bar', [
                ('id', models.AutoField(primary_key=True)),
                ('foo', models.ForeignKey('app.Foo', models.CASCADE, to_field='renamed_field')),
            ]),
        ]
        changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True}))
        # Right number/type of migrations?
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['RenameField'])
        self.assertOperationAttributes(changes, 'app', 0, 0, old_name='field', new_name='renamed_field') 
Example #28
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_field_preserved_db_column(self):
        """
        RenameField is used if a field is renamed and db_column equal to the
        old field's column is added.
        """
        before = [
            ModelState('app', 'Foo', [
                ('id', models.AutoField(primary_key=True)),
                ('field', models.IntegerField()),
            ]),
        ]
        after = [
            ModelState('app', 'Foo', [
                ('id', models.AutoField(primary_key=True)),
                ('renamed_field', models.IntegerField(db_column='field')),
            ]),
        ]
        changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True}))
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['RenameField', 'AlterField'])
        self.assertOperationAttributes(
            changes, 'app', 0, 0, model_name='foo', old_name='field', new_name='renamed_field',
        )
        self.assertOperationAttributes(changes, 'app', 0, 1, model_name='foo', name='renamed_field')
        self.assertEqual(changes['app'][0].operations[-1].field.deconstruct(), (
            'renamed_field', 'django.db.models.IntegerField', [], {'db_column': 'field'},
        )) 
Example #29
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_related_field_preserved_db_column(self):
        before = [
            ModelState('app', 'Foo', [
                ('id', models.AutoField(primary_key=True)),
            ]),
            ModelState('app', 'Bar', [
                ('id', models.AutoField(primary_key=True)),
                ('foo', models.ForeignKey('app.Foo', models.CASCADE)),
            ]),
        ]
        after = [
            ModelState('app', 'Foo', [
                ('id', models.AutoField(primary_key=True)),
            ]),
            ModelState('app', 'Bar', [
                ('id', models.AutoField(primary_key=True)),
                ('renamed_foo', models.ForeignKey('app.Foo', models.CASCADE, db_column='foo_id')),
            ]),
        ]
        changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True}))
        self.assertNumberMigrations(changes, 'app', 1)
        self.assertOperationTypes(changes, 'app', 0, ['RenameField', 'AlterField'])
        self.assertOperationAttributes(
            changes, 'app', 0, 0, model_name='bar', old_name='foo', new_name='renamed_foo',
        )
        self.assertOperationAttributes(changes, 'app', 0, 1, model_name='bar', name='renamed_foo')
        self.assertEqual(changes['app'][0].operations[-1].field.deconstruct(), (
            'renamed_foo',
            'django.db.models.ForeignKey',
            [],
            {'to': 'app.Foo', 'on_delete': models.CASCADE, 'db_column': 'foo_id'},
        )) 
Example #30
Source File: test_autodetector.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rename_model_with_fks_in_different_position(self):
        """
        #24537 - The order of fields in a model does not influence
        the RenameModel detection.
        """
        before = [
            ModelState("testapp", "EntityA", [
                ("id", models.AutoField(primary_key=True)),
            ]),
            ModelState("testapp", "EntityB", [
                ("id", models.AutoField(primary_key=True)),
                ("some_label", models.CharField(max_length=255)),
                ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)),
            ]),
        ]
        after = [
            ModelState("testapp", "EntityA", [
                ("id", models.AutoField(primary_key=True)),
            ]),
            ModelState("testapp", "RenamedEntityB", [
                ("id", models.AutoField(primary_key=True)),
                ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)),
                ("some_label", models.CharField(max_length=255)),
            ]),
        ]
        changes = self.get_changes(before, after, MigrationQuestioner({"ask_rename_model": True}))
        self.assertNumberMigrations(changes, "testapp", 1)
        self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"])
        self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB")