Python django.db.migrations.CreateModel() Examples
The following are 30 code examples for showing how to use django.db.migrations.CreateModel(). 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
Project: GTDWeb Author: lanbing510 File: optimizer.py License: GNU General Public License v2.0 | 6 votes |
def reduce_create_model_add_field(self, operation, other, in_between): if operation.name_lower == other.model_name_lower: # Don't allow optimizations of FKs through models they reference if hasattr(other.field, "rel") and other.field.rel: for between in in_between: # Check that it doesn't point to the model app_label, object_name = self.model_to_key(other.field.rel.to) if between.references_model(object_name, app_label): return None # Check that it's not through the model if getattr(other.field.rel, "through", None): app_label, object_name = self.model_to_key(other.field.rel.through) if between.references_model(object_name, app_label): return None # OK, that's fine return [ migrations.CreateModel( operation.name, fields=operation.fields + [(other.name, other.field)], options=operation.options, bases=operation.bases, managers=operation.managers, ) ]
Example 2
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 6 votes |
def test_create_model_add_field_not_through_m2m_through(self): """ AddField should NOT optimize into CreateModel if it's an M2M using a through that's created between them. """ # Note: The middle model is not actually a valid through model, # but that doesn't matter, as we never render it. self.assertDoesNotOptimize( [ migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]), migrations.CreateModel("LinkThrough", []), migrations.AddField( "Foo", "link", models.ManyToManyField("migrations.Link", through="migrations.LinkThrough") ), ], )
Example 3
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 6 votes |
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
Project: django-sqlserver Author: denisenkom File: test_writer.py License: MIT License | 6 votes |
def test_custom_operation(self): migration = type(str("Migration"), (migrations.Migration,), { "operations": [ custom_migration_operations.operations.TestOperation(), custom_migration_operations.operations.CreateModel(), migrations.CreateModel("MyModel", (), {}, (models.Model,)), custom_migration_operations.more_operations.TestOperation() ], "dependencies": [] }) writer = MigrationWriter(migration) output = writer.as_string() result = self.safe_exec(output) self.assertIn("custom_migration_operations", result) self.assertNotEqual( result['custom_migration_operations'].operations.TestOperation, result['custom_migration_operations'].more_operations.TestOperation )
Example 5
Project: django-sqlserver Author: denisenkom File: test_multidb.py License: MIT License | 6 votes |
def _test_create_model(self, app_label, should_run): """ CreateModel honors multi-db settings. """ operation = migrations.CreateModel( "Pony", [("id", models.AutoField(primary_key=True))], ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Test the database alteration self.assertTableNotExists("%s_pony" % app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if should_run: self.assertTableExists("%s_pony" % app_label) else: self.assertTableNotExists("%s_pony" % app_label) # And test reversal with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertTableNotExists("%s_pony" % app_label)
Example 6
Project: django-sqlserver Author: denisenkom File: test_operations.py License: MIT License | 6 votes |
def test_remove_field_m2m_with_through(self): project_state = self.set_up_test_model("test_rmflmmwt", second_model=True) self.assertTableNotExists("test_rmflmmwt_ponystables") project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[ migrations.CreateModel("PonyStables", fields=[ ("pony", models.ForeignKey('test_rmflmmwt.Pony', models.CASCADE)), ("stable", models.ForeignKey('test_rmflmmwt.Stable', models.CASCADE)), ]), migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables') ) ]) self.assertTableExists("test_rmflmmwt_ponystables") operations = [migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables")] self.apply_operations("test_rmflmmwt", project_state, operations=operations)
Example 7
Project: djongo Author: nesdis File: test_optimizer.py License: GNU Affero General Public License v3.0 | 6 votes |
def test_create_model_add_field_not_through_m2m_through(self): """ AddField should NOT optimize into CreateModel if it's an M2M using a through that's created between them. """ # Note: The middle model is not actually a valid through model, # but that doesn't matter, as we never render it. self.assertDoesNotOptimize( [ migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]), migrations.CreateModel("LinkThrough", []), migrations.AddField( "Foo", "link", models.ManyToManyField("migrations.Link", through="migrations.LinkThrough") ), ], )
Example 8
Project: djongo Author: nesdis File: test_optimizer.py License: GNU Affero General Public License v3.0 | 6 votes |
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 9
Project: djongo Author: nesdis File: test_writer.py License: GNU Affero General Public License v3.0 | 6 votes |
def test_custom_operation(self): migration = type("Migration", (migrations.Migration,), { "operations": [ custom_migration_operations.operations.TestOperation(), custom_migration_operations.operations.CreateModel(), migrations.CreateModel("MyModel", (), {}, (models.Model,)), custom_migration_operations.more_operations.TestOperation() ], "dependencies": [] }) writer = MigrationWriter(migration) output = writer.as_string() result = self.safe_exec(output) self.assertIn("custom_migration_operations", result) self.assertNotEqual( result['custom_migration_operations'].operations.TestOperation, result['custom_migration_operations'].more_operations.TestOperation )
Example 10
Project: djongo Author: nesdis File: test_multidb.py License: GNU Affero General Public License v3.0 | 6 votes |
def _test_create_model(self, app_label, should_run): """ CreateModel honors multi-db settings. """ operation = migrations.CreateModel( "Pony", [("id", models.AutoField(primary_key=True))], ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Test the database alteration self.assertTableNotExists("%s_pony" % app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if should_run: self.assertTableExists("%s_pony" % app_label) else: self.assertTableNotExists("%s_pony" % app_label) # And test reversal with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertTableNotExists("%s_pony" % app_label)
Example 11
Project: djongo Author: nesdis File: test_operations.py License: GNU Affero General Public License v3.0 | 6 votes |
def test_remove_field_m2m_with_through(self): project_state = self.set_up_test_model("test_rmflmmwt", second_model=True) self.assertTableNotExists("test_rmflmmwt_ponystables") project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[ migrations.CreateModel("PonyStables", fields=[ ("pony", models.ForeignKey('test_rmflmmwt.Pony', models.CASCADE)), ("stable", models.ForeignKey('test_rmflmmwt.Stable', models.CASCADE)), ]), migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables') ) ]) self.assertTableExists("test_rmflmmwt_ponystables") operations = [migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables")] self.apply_operations("test_rmflmmwt", project_state, operations=operations)
Example 12
Project: djongo Author: nesdis File: test_operations.py License: GNU Affero General Public License v3.0 | 6 votes |
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 13
Project: djongo Author: nesdis File: test_operations.py License: GNU Affero General Public License v3.0 | 6 votes |
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 14
Project: GTDWeb Author: lanbing510 File: optimizer.py License: GNU General Public License v2.0 | 5 votes |
def reduce_model_create_delete(self, operation, other, in_between): """ Folds a CreateModel and a DeleteModel into nothing. """ if (operation.name_lower == other.name_lower and not operation.options.get("proxy", False)): return []
Example 15
Project: GTDWeb Author: lanbing510 File: optimizer.py License: GNU General Public License v2.0 | 5 votes |
def reduce_model_create_rename(self, operation, other, in_between): """ Folds a model rename into its create """ if operation.name_lower == other.old_name_lower: return [ migrations.CreateModel( other.new_name, fields=operation.fields, options=operation.options, bases=operation.bases, managers=operation.managers, ) ]
Example 16
Project: GTDWeb Author: lanbing510 File: optimizer.py License: GNU General Public License v2.0 | 5 votes |
def reduce_create_model_alter_field(self, operation, other, in_between): if operation.name_lower == other.model_name_lower: return [ migrations.CreateModel( operation.name, fields=[ (n, other.field if n == other.name else v) for n, v in operation.fields ], options=operation.options, bases=operation.bases, managers=operation.managers, ) ]
Example 17
Project: GTDWeb Author: lanbing510 File: optimizer.py License: GNU General Public License v2.0 | 5 votes |
def reduce_create_model_rename_field(self, operation, other, in_between): if operation.name_lower == other.model_name_lower: return [ migrations.CreateModel( operation.name, fields=[ (other.new_name if n == other.old_name else n, v) for n, v in operation.fields ], options=operation.options, bases=operation.bases, managers=operation.managers, ) ]
Example 18
Project: GTDWeb Author: lanbing510 File: executor.py License: GNU General Public License v2.0 | 5 votes |
def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel). """ # Bail if the migration isn't the first one in its app if [name for app, name in migration.dependencies if app == migration.app_label]: return False, project_state if project_state is None: after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_migration = False # Make sure all create model are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.db_table not in self.connection.introspection.table_names(self.connection.cursor()): return False, project_state found_create_migration = True # If we get this far and we found at least one CreateModel migration, # the migration is considered implicitly applied. return found_create_migration, after_state
Example 19
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_delete_model(self): """ CreateModel and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]), migrations.DeleteModel("Foo"), ], [], )
Example 20
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_rename_model(self): """ CreateModel should absorb RenameModels. """ managers = [('objects', EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameModel("Foo", "Bar"), ], [ migrations.CreateModel( "Bar", [("name", models.CharField(max_length=255))], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ) ], )
Example 21
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_alter_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel('Foo', fields=[]), migrations.AlterModelOptions(name='Foo', options={'verbose_name_plural': 'Foozes'}), ], [ migrations.CreateModel('Foo', fields=[], options={'verbose_name_plural': 'Foozes'}), ] )
Example 22
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def _test_create_alter_foo_delete_model(self, alter_foo): """ CreateModel, AlterModelTable, AlterUniqueTogether/AlterIndexTogether/ AlterOrderWithRespectTo, and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]), migrations.AlterModelTable("Foo", "woohoo"), alter_foo, migrations.DeleteModel("Foo"), ], [], )
Example 23
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_model_add_field(self): """ AddField should optimize into CreateModel. """ managers = [('objects', EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), migrations.AddField("Foo", "age", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), ], )
Example 24
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_model_alter_field(self): """ AlterField should optimize into CreateModel. """ managers = [('objects', EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), migrations.AlterField("Foo", "name", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.IntegerField()), ], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), ], )
Example 25
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_model_rename_field(self): """ RenameField should optimize into CreateModel. """ managers = [('objects', EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameField("Foo", "name", "title"), ], [ migrations.CreateModel( name="Foo", fields=[ ("title", models.CharField(max_length=255)), ], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), ], )
Example 26
Project: django-sqlserver Author: denisenkom File: test_optimizer.py License: MIT License | 5 votes |
def test_create_model_remove_field(self): """ RemoveField should optimize into CreateModel. """ managers = [('objects', EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), migrations.RemoveField("Foo", "age"), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ], options={'verbose_name': 'Foo'}, bases=(UnicodeModel,), managers=managers, ), ], )
Example 27
Project: django-sqlserver Author: denisenkom File: test_multidb.py License: MIT License | 5 votes |
def test_create_model(self): """ Test when router doesn't have an opinion (i.e. CreateModel should run). """ self._test_create_model("test_mltdb_crmo", should_run=True)
Example 28
Project: django-sqlserver Author: denisenkom File: test_multidb.py License: MIT License | 5 votes |
def test_create_model2(self): """ Test when router returns False (i.e. CreateModel shouldn't run). """ self._test_create_model("test_mltdb_crmo2", should_run=False)
Example 29
Project: django-sqlserver Author: denisenkom File: test_operations.py License: MIT License | 5 votes |
def test_create_model(self): """ Tests the CreateModel operation. Most other tests use this operation as part of setup, so check failures here first. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) self.assertEqual(operation.describe(), "Create model Pony") # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2].keys()), ["fields", "name"]) # And default manager not in set operation = migrations.CreateModel("Foo", fields=[], managers=[("objects", models.Manager())]) definition = operation.deconstruct() self.assertNotIn('managers', definition[2])
Example 30
Project: django-sqlserver Author: denisenkom File: test_operations.py License: MIT License | 5 votes |
def test_create_model_with_duplicate_field_name(self): with self.assertRaisesMessage(ValueError, 'Found duplicate value pink in CreateModel fields argument.'): migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.TextField()), ("pink", models.IntegerField(default=1)), ], )