Python django.db.migrations.state.ProjectState.from_apps() Examples
The following are 18
code examples of django.db.migrations.state.ProjectState.from_apps().
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.ProjectState
, or try the search function
.
Example #1
Source File: tests.py From django-composite-foreignkey with GNU General Public License v3.0 | 6 votes |
def test_total_deconstruct(self): loader = MigrationLoader(None, load=True, ignore_no_migrations=True) loader.disk_migrations = {t: v for t, v in loader.disk_migrations.items() if t[0] != 'testapp'} app_labels = {"testapp"} questioner = NonInteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=True) autodetector = MigrationAutodetector( loader.project_state(), ProjectState.from_apps(apps), questioner, ) # Detect changes changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name="my_fake_migration_for_test_deconstruct", ) self.assertGreater(len(changes), 0) for app_label, app_migrations in changes.items(): for migration in app_migrations: # Describe the migration writer = MigrationWriter(migration) migration_string = writer.as_string() self.assertNotEqual(migration_string, "")
Example #2
Source File: has_missing_migrations.py From django-react-boilerplate with MIT License | 6 votes |
def handle(self, *args, **options): changed = set() self.stdout.write("Checking...") for db in settings.DATABASES.keys(): try: executor = MigrationExecutor(connections[db]) except OperationalError: sys.exit("Unable to check migrations: cannot connect to database\n") autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changed.update(autodetector.changes(graph=executor.loader.graph).keys()) changed -= set(options["ignore"]) if changed: sys.exit( "Apps with model changes but no corresponding migration file: %(changed)s\n" % {"changed": list(changed)} ) else: sys.stdout.write("All migration files present\n")
Example #3
Source File: test_middleware.py From django-request-profiler with MIT License | 6 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=ProjectState.from_apps(apps), ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( "Your models have changes that are not yet reflected " "in a migration. You should add them now." )
Example #4
Source File: migrations.py From django-postgres-extra with MIT License | 6 votes |
def add_field(field, filters: List[str]): """Adds the specified field to a model. Arguments: field: The field to add to a model. filters: List of strings to filter SQL statements on. """ model = define_fake_model() state = migrations.state.ProjectState.from_apps(apps) apply_migration([migrations.CreateModel(model.__name__, fields=[])], state) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.AddField(model.__name__, "title", field)], state ) yield calls
Example #5
Source File: patched_project_state.py From django-postgres-extra with MIT License | 6 votes |
def patched_project_state(): """Patches the standard Django :see:ProjectState.from_apps for the duration of the context. The patch intercepts the `from_apps` function to control how model state is creatd. We want to use our custom model state classes for certain types of models. We have to do this because there is no way in Django to extend the project state otherwise. """ from_apps_module_path = "django.db.migrations.state" from_apps_class_path = f"{from_apps_module_path}.ProjectState" from_apps_path = f"{from_apps_class_path}.from_apps" with mock.patch(from_apps_path, new=project_state_from_apps): yield
Example #6
Source File: missing_migrations.py From lego with MIT License | 5 votes |
def run(self, *args, **kwargs): changed = set() log.info("Checking DB migrations") for db in settings.DATABASES.keys(): try: executor = MigrationExecutor(connections[db]) except OperationalError: log.critical("Unable to check migrations, cannot connect to database") sys.exit(1) autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps) ) changed.update(autodetector.changes(graph=executor.loader.graph).keys()) if changed: log.critical( "Apps with model changes but no corresponding " f"migration file: {list(changed)}" ) sys.exit(1) else: log.info("All migration files present")
Example #7
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def rename_field(field, filters: List[str]): """Renames a field from one name to the other. Arguments: field: Field to be renamed. filters: List of strings to filter SQL statements on. """ model = define_fake_model({"title": field}) state = migrations.state.ProjectState.from_apps(apps) apply_migration( [ migrations.CreateModel( model.__name__, fields=[("title", field.clone())] ) ], state, ) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.RenameField(model.__name__, "title", "newtitle")], state ) yield calls
Example #8
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
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
Example #9
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def alter_db_table(field, filters: List[str]): """Creates a model with the specified field and then renames the database table. Arguments: field: The field to include into the model. filters: List of strings to filter SQL statements on. """ model = define_fake_model() state = migrations.state.ProjectState.from_apps(apps) apply_migration( [ migrations.CreateModel( model.__name__, fields=[("title", field.clone())] ) ], state, ) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.AlterModelTable(model.__name__, "NewTableName")], state ) yield calls
Example #10
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def make_migration(app_label="tests", from_state=None, to_state=None): """Generates migrations based on the specified app's state.""" app_labels = [app_label] loader = MigrationLoader(None, ignore_no_migrations=True) loader.check_consistent_history(connection) questioner = NonInteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=False ) autodetector = MigrationAutodetector( from_state or loader.project_state(), to_state or ProjectState.from_apps(apps), questioner, ) changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name="test", ) changes_for_app = changes.get(app_label) if not changes_for_app or len(changes_for_app) == 0: return None return changes_for_app[0]
Example #11
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def apply_migration(operations, state=None, backwards: bool = False): """Executes the specified migration operations using the specified schema editor. Arguments: operations: The migration operations to execute. state: The state state to use during the migrations. backwards: Whether to apply the operations in reverse (backwards). """ state = state or migrations.state.ProjectState.from_apps(apps) class Migration(migrations.Migration): pass Migration.operations = operations migration = Migration("migration", "tests") executor = MigrationExecutor(connection) if not backwards: executor.apply_migration(state, migration) else: executor.unapply_migration(state, migration) return migration
Example #12
Source File: test_migration.py From django-tsvector-field with BSD 3-Clause "New" or "Revised" License | 5 votes |
def migrate(self, ops, state=None): class Migration(migrations.Migration): operations = ops migration = Migration('name', 'tests') inject_trigger_operations([(migration, False)]) with connection.schema_editor() as schema_editor: return migration.apply(state or ProjectState.from_apps(self.apps), schema_editor)
Example #13
Source File: test_migrations.py From django-request-token with MIT License | 5 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=ProjectState.from_apps(apps), ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( "Your models have changes that are not yet reflected " "in a migration. You should add them now." )
Example #14
Source File: test_migrations.py From elasticsearch-django with MIT License | 5 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" current_models_state = ProjectState.from_apps(apps) # skip tracking changes for TestModel current_models_state.remove_model("tests", "testmodel") migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=current_models_state ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( "Your models have changes that are not yet reflected " "in a migration. You should add them now." )
Example #15
Source File: check_missing_migrations.py From django-andablog with BSD 2-Clause "Simplified" License | 5 votes |
def handle(self, *args, **kwargs): changed = set() ignore_list = ['authtools'] # dependencies that we don't care about migrations for (usually for testing only) self.stdout.write("Checking...") for db in settings.DATABASES.keys(): try: executor = MigrationExecutor(connections[db]) except OperationalError: sys.exit("Unable to check migrations: cannot connect to database\n") autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changed.update(autodetector.changes(graph=executor.loader.graph).keys()) for ignore in ignore_list: if ignore in changed: changed.remove(ignore) if changed: sys.exit("Apps with model changes but no corresponding migration file: %(changed)s\n" % { 'changed': list(changed) }) else: sys.stdout.write("All migration files present\n")
Example #16
Source File: test_migrations.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test__migrations(self): app_labels = set(app.label for app in apps.get_app_configs() if app.name.startswith('wagtail.')) for app_label in app_labels: apps.get_app_config(app_label.split('.')[-1]) loader = MigrationLoader(None, ignore_no_migrations=True) conflicts = dict( (app_label, conflict) for app_label, conflict in loader.detect_conflicts().items() if app_label in app_labels ) if conflicts: name_str = "; ".join("%s in %s" % (", ".join(names), app) for app, names in conflicts.items()) self.fail("Conflicting migrations detected (%s)." % name_str) autodetector = MigrationAutodetector( loader.project_state(), ProjectState.from_apps(apps), MigrationQuestioner(specified_apps=app_labels, dry_run=True), ) changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, ) if changes: migrations = '\n'.join(( ' {migration}\n{changes}'.format( migration=migration, changes='\n'.join(' {0}'.format(operation.describe()) for operation in migration.operations)) for (_, migrations) in changes.items() for migration in migrations)) self.fail('Model changes with no migrations detected:\n%s' % migrations)
Example #17
Source File: test_migrations.py From django-package-monitor with MIT License | 5 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=ProjectState.from_apps(apps) ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( 'Your models have changes that are not yet reflected ' 'in a migration. You should add them now.' )
Example #18
Source File: test_make_migrations.py From django-postgres-extra with MIT License | 4 votes |
def test_make_migration_field_operations_view_models( fake_app, define_view_model ): """Tests whether field operations against a (materialized) view are always wrapped in the :see:ApplyState operation so that they don't actually get applied to the database, yet Django applies to them to the project state. This is important because you can't actually alter/add or delete fields from a (materialized) view. """ underlying_model = get_fake_model( {"first_name": models.TextField(), "last_name": models.TextField()}, meta_options=dict(app_label=fake_app.name), ) model = define_view_model( fields={"first_name": models.TextField()}, view_options=dict(query=underlying_model.objects.all()), meta_options=dict(app_label=fake_app.name), ) state_1 = ProjectState.from_apps(apps) migration = make_migration(model._meta.app_label) apply_migration(migration.operations, state_1) # add a field to the materialized view last_name_field = models.TextField(null=True) last_name_field.contribute_to_class(model, "last_name") migration = make_migration(model._meta.app_label, from_state=state_1) assert len(migration.operations) == 1 assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AddField) # alter the field on the materialized view state_2 = ProjectState.from_apps(apps) last_name_field = models.TextField(null=True, blank=True) last_name_field.contribute_to_class(model, "last_name") migration = make_migration(model._meta.app_label, from_state=state_2) assert len(migration.operations) == 1 assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, AlterField) # remove the field from the materialized view migration = make_migration( model._meta.app_label, from_state=ProjectState.from_apps(apps), to_state=state_1, ) assert isinstance(migration.operations[0], operations.ApplyState) assert isinstance(migration.operations[0].state_operation, RemoveField)