Python django.db.router.db_for_read() Examples
The following are 30
code examples of django.db.router.db_for_read().
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.router
, or try the search function
.
Example #1
Source File: related.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def validate(self, value, model_instance): if self.rel.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return using = router.db_for_read(model_instance.__class__, instance=model_instance) qs = self.rel.to._default_manager.using(using).filter( **{self.rel.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={ 'model': self.rel.to._meta.verbose_name, 'pk': value, 'field': self.rel.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
Example #2
Source File: db.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) if settings.USE_TZ: now = datetime.utcnow() else: now = datetime.now() now = now.replace(microsecond=0) with connections[db].cursor() as cursor: cursor.execute("SELECT cache_key FROM %s " "WHERE cache_key = %%s and expires > %%s" % table, [key, connections[db].ops.value_to_db_datetime(now)]) return cursor.fetchone() is not None
Example #3
Source File: related.py From python2017 with MIT License | 6 votes |
def validate(self, value, model_instance): if self.remote_field.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._default_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={ 'model': self.remote_field.model._meta.verbose_name, 'pk': value, 'field': self.remote_field.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
Example #4
Source File: related.py From bioforum with MIT License | 6 votes |
def validate(self, value, model_instance): if self.remote_field.parent_link: return super().validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._default_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={ 'model': self.remote_field.model._meta.verbose_name, 'pk': value, 'field': self.remote_field.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
Example #5
Source File: related.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def validate(self, value, model_instance): if self.remote_field.parent_link: return super().validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._default_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={ 'model': self.remote_field.model._meta.verbose_name, 'pk': value, 'field': self.remote_field.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
Example #6
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_many(self, keys, version=None): made_key_to_key = {self.make_key(key, version=version): key for key in keys} made_keys = list(made_key_to_key.keys()) for key in made_keys: self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute( self._get_many_query.format( table=table, list_sql=get_list_sql(made_keys) ), made_keys + [self._now()], ) rows = cursor.fetchall() data = {} for made_key, value, value_type in rows: key = made_key_to_key[made_key] data[key] = self.decode(value, value_type) return data
Example #7
Source File: related.py From python with Apache License 2.0 | 6 votes |
def validate(self, value, model_instance): if self.remote_field.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._default_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={ 'model': self.remote_field.model._meta.verbose_name, 'pk': value, 'field': self.remote_field.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
Example #8
Source File: related.py From openhgsenti with Apache License 2.0 | 6 votes |
def validate(self, value, model_instance): if self.remote_field.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return using = router.db_for_read(model_instance.__class__, instance=model_instance) qs = self.remote_field.model._default_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={ 'model': self.remote_field.model._meta.verbose_name, 'pk': value, 'field': self.remote_field.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
Example #9
Source File: db.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() if settings.USE_TZ: now = datetime.utcnow() else: now = datetime.now() now = now.replace(microsecond=0) cursor.execute("SELECT cache_key FROM %s " "WHERE cache_key = %%s and expires > %%s" % table, [key, connections[db].ops.value_to_db_datetime(now)]) return cursor.fetchone() is not None
Example #10
Source File: db.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute("SELECT cache_key, value, expires FROM %s " "WHERE cache_key = %%s" % table, [key]) row = cursor.fetchone() if row is None: return default now = timezone.now() if row[2] < now: db = router.db_for_write(self.cache_model_class) cursor = connections[db].cursor() cursor.execute("DELETE FROM %s " "WHERE cache_key = %%s" % table, [key]) transaction.commit_unless_managed(using=db) return default value = connections[db].ops.process_clob(row[1]) return pickle.loads(base64.b64decode(force_bytes(value)))
Example #11
Source File: manager.py From python2017 with MIT License | 5 votes |
def db(self): return self._db or router.db_for_read(self.model, **self._hints) ####################### # PROXIES TO QUERYSET # #######################
Example #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def db_for_read(self, model, **hints): raise AttributeError
Example #13
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def test_foreign_key_validation(self): "ForeignKey.validate() uses the correct database" mickey = Person.objects.using('other').create(name="Mickey") pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey) self.assertIsNone(pluto.full_clean()) # Any router that accesses `model` in db_for_read() works here.
Example #14
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def test_foreign_key_validation_with_router(self): """ ForeignKey.validate() passes `model` to db_for_read() even if model_instance=None. """ if django.VERSION < (1, 11, 0): self.skipTest("TODO fix AttributeError: type object 'NoneType' has no attribute '_meta'") mickey = Person.objects.create(name="Mickey") owner_field = Pet._meta.get_field('owner') self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
Example #15
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def test_partial_router(self): "A router can choose to implement a subset of methods" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # First check the baseline behavior. self.assertEqual(router.db_for_read(User), 'other') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'default') self.assertEqual(router.db_for_write(Book), 'default') self.assertTrue(router.allow_relation(dive, dive)) self.assertTrue(router.allow_migrate_model('default', User)) self.assertTrue(router.allow_migrate_model('default', Book)) with override_settings(DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]): self.assertEqual(router.db_for_read(User), 'default') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'writer') self.assertEqual(router.db_for_write(Book), 'writer') self.assertTrue(router.allow_relation(dive, dive)) self.assertFalse(router.allow_migrate_model('default', User)) self.assertTrue(router.allow_migrate_model('default', Book))
Example #16
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def db_for_read(self, model, **hints): raise AttributeError
Example #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_refresh_router_instance_hint(self): router = Mock() router.db_for_read.return_value = None book = Book.objects.create(title='Dive Into Python', published=datetime.date(1957, 10, 12)) with self.settings(DATABASE_ROUTERS=[router]): book.refresh_from_db() router.db_for_read.assert_called_once_with(Book, instance=book)
Example #18
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_foreign_key_validation(self): "ForeignKey.validate() uses the correct database" mickey = Person.objects.using('other').create(name="Mickey") pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey) self.assertIsNone(pluto.full_clean()) # Any router that accesses `model` in db_for_read() works here.
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_foreign_key_validation_with_router(self): """ ForeignKey.validate() passes `model` to db_for_read() even if model_instance=None. """ mickey = Person.objects.create(name="Mickey") owner_field = Pet._meta.get_field('owner') self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
Example #20
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_partial_router(self): "A router can choose to implement a subset of methods" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # First check the baseline behavior. self.assertEqual(router.db_for_read(User), 'other') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'default') self.assertEqual(router.db_for_write(Book), 'default') self.assertTrue(router.allow_relation(dive, dive)) self.assertTrue(router.allow_migrate_model('default', User)) self.assertTrue(router.allow_migrate_model('default', Book)) with override_settings(DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]): self.assertEqual(router.db_for_read(User), 'default') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'writer') self.assertEqual(router.db_for_write(Book), 'writer') self.assertTrue(router.allow_relation(dive, dive)) self.assertFalse(router.allow_migrate_model('default', User)) self.assertTrue(router.allow_migrate_model('default', Book))
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def db_for_read(self, model, **hints): raise AttributeError
Example #22
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_foreign_key_validation(self): "ForeignKey.validate() uses the correct database" mickey = Person.objects.using('other').create(name="Mickey") pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey) self.assertIsNone(pluto.full_clean()) # Any router that accesses `model` in db_for_read() works here.
Example #23
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_foreign_key_validation_with_router(self): """ ForeignKey.validate() passes `model` to db_for_read() even if model_instance=None. """ mickey = Person.objects.create(name="Mickey") owner_field = Pet._meta.get_field('owner') self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
Example #24
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_partial_router(self): "A router can choose to implement a subset of methods" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # First check the baseline behavior. self.assertEqual(router.db_for_read(User), 'other') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'default') self.assertEqual(router.db_for_write(Book), 'default') self.assertTrue(router.allow_relation(dive, dive)) self.assertTrue(router.allow_migrate_model('default', User)) self.assertTrue(router.allow_migrate_model('default', Book)) with override_settings(DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]): self.assertEqual(router.db_for_read(User), 'default') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'writer') self.assertEqual(router.db_for_write(Book), 'writer') self.assertTrue(router.allow_relation(dive, dive)) self.assertFalse(router.allow_migrate_model('default', User)) self.assertTrue(router.allow_migrate_model('default', Book))
Example #25
Source File: manager.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def db(self): return self._db or router.db_for_read(self.model, **self._hints) ####################### # PROXIES TO QUERYSET # #######################
Example #26
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_with_prefix(self, prefix, version=None): if self.reverse_key_func is None: raise ValueError( "To use the _with_prefix commands with a custom KEY_FUNCTION, " "you need to specify a custom REVERSE_KEY_FUNCTION too." ) if version is None: version = self.version db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) prefix = self.make_key(prefix + "%", version=version) version = str(version) with connections[db].cursor() as cursor: cursor.execute( """SELECT cache_key, value, value_type FROM {table} WHERE cache_key LIKE %s AND expires >= %s""".format( table=table ), (prefix, self._now()), ) rows = cursor.fetchall() data = {} for made_key, value, value_type in rows: key, key_prefix, key_version = self.reverse_key_func(made_key) data[key] = self.decode(value, value_type) return data
Example #27
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 5 votes |
def keys_with_prefix(self, prefix, version=None): if self.reverse_key_func is None: raise ValueError( "To use the _with_prefix commands with a custom KEY_FUNCTION, " "you need to specify a custom REVERSE_KEY_FUNCTION too." ) if version is None: version = self.version db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) prefix = self.make_key(prefix + "%", version=version) with connections[db].cursor() as cursor: cursor.execute( """SELECT cache_key FROM {table} WHERE cache_key LIKE %s AND expires >= %s""".format( table=table ), (prefix, self._now()), ) rows = cursor.fetchall() full_keys = {row[0] for row in rows} keys = {} for full_key in full_keys: key, key_prefix, key_version = self.reverse_key_func(full_key) if key_version == version: keys[key] = key_version return set(keys.keys())
Example #28
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 5 votes |
def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute(self._has_key_query.format(table=table), (key, self._now())) return cursor.fetchone() is not None
Example #29
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) db = router.db_for_read(self.cache_model_class) table = connections[db].ops.quote_name(self._table) with connections[db].cursor() as cursor: cursor.execute(self._get_query.format(table=table), (key, self._now())) row = cursor.fetchone() if row is None: return default else: value, value_type = row return self.decode(value, value_type)
Example #30
Source File: manager.py From openhgsenti with Apache License 2.0 | 5 votes |
def db(self): return self._db or router.db_for_read(self.model, **self._hints) ####################### # PROXIES TO QUERYSET # #######################