Python django.db.connection() Examples
The following are 30
code examples of django.db.connection().
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
, or try the search function
.
Example #1
Source File: utils.py From karrot-backend with GNU Affero General Public License v3.0 | 7 votes |
def setUp(self): assert self.migrate_from and self.migrate_to, \ "TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__) executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(self.migrate_from).apps # Reverse to the original migration executor.migrate(self.migrate_from) self.setUpBeforeMigration(old_apps) # Run the migration to test executor = MigrationExecutor(connection) executor.loader.build_graph() # reload. executor.migrate(self.migrate_to) self.apps = executor.loader.project_state(self.migrate_to).apps
Example #2
Source File: helper.py From byro with Apache License 2.0 | 6 votes |
def setUp(self): assert ( self.migrate_from and self.migrate_to ), "TestCase '{}' must define migrate_from and migrate_to properties".format( type(self).__name__ ) self.migrate_from = [(self.app, self.migrate_from)] self.migrate_to = [(self.app, self.migrate_to)] executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(self.migrate_from).apps # Reverse to the original migration executor.migrate(self.migrate_from) if self.migrate_fixtures: self.load_fixtures(self.migrate_fixtures, apps=old_apps) self.setUpBeforeMigration(old_apps) # Run the migration to test executor = MigrationExecutor(connection) executor.loader.build_graph() # reload. executor.migrate(self.migrate_to) self.apps = executor.loader.project_state(self.migrate_to).apps
Example #3
Source File: conftest.py From normandy with Mozilla Public License 2.0 | 6 votes |
def migrations(transactional_db): """ This fixture returns a helper object to test Django data migrations. Based on: https://gist.github.com/bennylope/82a6088c02fefdd47e18f3c04ec167af """ class Migrator(object): def migrate(self, app, to): migration = [(app, to)] executor = MigrationExecutor(connection) executor.migrate(migration) return executor.loader.project_state(migration).apps def reset(self): call_command("migrate", no_input=True) return Migrator()
Example #4
Source File: test_classes.py From zulip with Apache License 2.0 | 6 votes |
def setUp(self) -> None: assert self.migrate_from and self.migrate_to, \ f"TestCase '{type(self).__name__}' must define migrate_from and migrate_to properties" migrate_from: List[Tuple[str, str]] = [(self.app, self.migrate_from)] migrate_to: List[Tuple[str, str]] = [(self.app, self.migrate_to)] executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(migrate_from).apps # Reverse to the original migration executor.migrate(migrate_from) self.setUpBeforeMigration(old_apps) # Run the migration to test executor = MigrationExecutor(connection) executor.loader.build_graph() # reload. executor.migrate(migrate_to) self.apps = executor.loader.project_state(migrate_to).apps
Example #5
Source File: util.py From donation-tracker with Apache License 2.0 | 6 votes |
def setUp(self): assert ( self.migrate_from and self.migrate_to ), "TestCase '{}' must define migrate_from and migrate_to properties".format( type(self).__name__ ) self.migrate_from = [(self.app, self.migrate_from)] self.migrate_to = [(self.app, self.migrate_to)] executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(self.migrate_from).apps # Reverse to the original migration executor.migrate(self.migrate_from) self.setUpBeforeMigration(old_apps) # Run the migration to test executor = MigrationExecutor(connection) executor.loader.build_graph() # reload. executor.migrate(self.migrate_to) self.apps = executor.loader.project_state(self.migrate_to).apps
Example #6
Source File: utils.py From django-rest-framework-simplejwt with MIT License | 6 votes |
def setUp(self): self.migrate_from = [self.migrate_from] self.migrate_to = [self.migrate_to] # Reverse to the original migration executor = MigrationExecutor(connection) executor.migrate(self.migrate_from) old_apps = executor.loader.project_state(self.migrate_from).apps self.setUpBeforeMigration(old_apps) # Run the migration to test executor.loader.build_graph() executor.migrate(self.migrate_to) self.apps = executor.loader.project_state(self.migrate_to).apps
Example #7
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 #8
Source File: base.py From site with MIT License | 5 votes |
def setUpTestData(cls): """ Injects data into the test database prior to the migration we're trying to test. This class methods reverts the test database back to the state of the last migration file prior to the migrations we want to test. It will then allow the user to inject data into the test database by calling the `setUpMigrationData` hook. After the data has been injected, it will apply the migrations we want to test and call the `setUpPostMigrationData` hook. The user can now test if the migration correctly migrated the injected test data. """ if not cls.app: raise ValueError("The `app` attribute was not set.") if not cls.migration_prior or not cls.migration_target: raise ValueError("Both ` migration_prior` and `migration_target` need to be set.") cls.migrate_from = [(cls.app, cls.migration_prior)] cls.migrate_to = [(cls.app, cls.migration_target)] # Reverse to database state prior to the migrations we want to test executor = MigrationExecutor(connection) executor.migrate(cls.migrate_from) # Call the data injection hook with the current state of the project old_apps = executor.loader.project_state(cls.migrate_from).apps cls.setUpMigrationData(old_apps) # Run the migrations we want to test executor = MigrationExecutor(connection) executor.loader.build_graph() executor.migrate(cls.migrate_to) # Save the project state so we're able to work with the correct model states cls.apps = executor.loader.project_state(cls.migrate_to).apps # Call `setUpPostMigrationData` to potentially set up post migration data used in testing cls.setUpPostMigrationData(cls.apps)
Example #9
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def get_db_converters(self, connection): converters = super().get_db_converters(connection) if connection.features.interprets_empty_strings_as_nulls: converters += [self.convert_empty_strings] return converters
Example #10
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def _get_m2m_db_table(self, opts): """ Function that can be curried to provide the m2m table name for this relation. """ if self.remote_field.through is not None: return self.remote_field.through._meta.db_table elif self.db_table: return self.db_table else: m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name) return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
Example #11
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def db_check(self, connection): return None
Example #12
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def db_parameters(self, connection): return {"type": None, "check": None}
Example #13
Source File: related.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): if not prepared: value = self.get_prep_lookup(lookup_type, value) if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): # If the value has a relabel_aliases method, it will need to # be invoked before the final SQL is evaluated if hasattr(value, 'relabel_aliases'): return value if hasattr(value, 'as_sql'): sql, params = value.as_sql() else: sql, params = value._as_sql(connection=connection) return QueryWrapper(('(%s)' % sql), params) # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return [self._pk_trace(value, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared)] if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type)
Example #14
Source File: related.py From python with Apache License 2.0 | 5 votes |
def db_parameters(self, connection): return {"type": None, "check": None}
Example #15
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def db_check(self, connection): return []
Example #16
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 #17
Source File: execution.py From axcell with Apache License 2.0 | 5 votes |
def q(query, limit=10, index_col=None): if limit is not None: query = query.rstrip(" ;") + f" LIMIT {limit}" return pd.read_sql(query, connection, index_col=index_col)
Example #18
Source File: related.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def db_type(self, connection): # The database column type of a ForeignKey is the column type # of the field to which it points. An exception is if the ForeignKey # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField, # in which case the column type is simply that of an IntegerField. # If the database needs similar types for key fields however, the only # thing we can do is making AutoField an IntegerField. rel_field = self.rel.get_related_field() if (isinstance(rel_field, AutoField) or (not connection.features.related_fields_match_type and isinstance(rel_field, (PositiveIntegerField, PositiveSmallIntegerField)))): return IntegerField().db_type(connection=connection) return rel_field.db_type(connection=connection)
Example #19
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def convert_empty_strings(self, value, expression, connection): if (not value) and isinstance(value, str): return None return value
Example #20
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def db_parameters(self, connection): return {"type": self.db_type(connection), "check": self.db_check(connection)}
Example #21
Source File: related.py From python with Apache License 2.0 | 5 votes |
def db_type(self, connection): # By default related field will not have a column as it relates to # columns from another table. return None
Example #22
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def get_db_prep_value(self, value, connection, prepared=False): return self.target_field.get_db_prep_value(value, connection, prepared)
Example #23
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def get_db_prep_save(self, value, connection): if value is None or (value == '' and (not self.target_field.empty_strings_allowed or connection.features.interprets_empty_strings_as_nulls)): return None else: return self.target_field.get_db_prep_save(value, connection=connection)
Example #24
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def get_extra_restriction(self, where_class, alias, related_alias): """ Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown. A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching. """ return None
Example #25
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def db_type(self, connection): # By default related field will not have a column as it relates to # columns from another table. return None
Example #26
Source File: test_django.py From python-dockerflow with Mozilla Public License 2.0 | 5 votes |
def test_check_database_connected_unsuable(mocker): mocker.patch("django.db.connection.is_usable", return_value=False) errors = checks.check_database_connected([]) assert len(errors) == 1 assert errors[0].id == health.ERROR_UNUSABLE_DATABASE
Example #27
Source File: test_django.py From python-dockerflow with Mozilla Public License 2.0 | 5 votes |
def test_check_database_connected_misconfigured(mocker): ensure_connection = mocker.patch("django.db.connection.ensure_connection") ensure_connection.side_effect = ImproperlyConfigured errors = checks.check_database_connected([]) assert len(errors) == 1 assert errors[0].id == health.ERROR_MISCONFIGURED_DATABASE
Example #28
Source File: test_django.py From python-dockerflow with Mozilla Public License 2.0 | 5 votes |
def test_check_database_connected_cannot_connect(mocker): ensure_connection = mocker.patch("django.db.connection.ensure_connection") ensure_connection.side_effect = OperationalError errors = checks.check_database_connected([]) assert len(errors) == 1 assert errors[0].id == health.ERROR_CANNOT_CONNECT_DATABASE
Example #29
Source File: test_django.py From python-dockerflow with Mozilla Public License 2.0 | 5 votes |
def test_lbheartbeat_makes_no_db_queries(dockerflow_middleware, rf): queries = CaptureQueriesContext(connection) request = rf.get("/__lbheartbeat__") with queries: response = dockerflow_middleware.process_request(request) assert response.status_code == 200 assert len(queries) == 0
Example #30
Source File: test_migrations.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def _get_apps_for_migration(self, migration_states): loader = MigrationLoader(connection) full_names = [] for app_name, migration_name in migration_states: if migration_name != 'zero': migration_name = loader.get_migration_by_prefix( app_name, migration_name).name full_names.append((app_name, migration_name)) state = loader.project_state(full_names) return state.apps