本文整理汇总了Python中django.db.router.db_for_write方法的典型用法代码示例。如果您正苦于以下问题:Python router.db_for_write方法的具体用法?Python router.db_for_write怎么用?Python router.db_for_write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.router
的用法示例。
在下文中一共展示了router.db_for_write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_request
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
示例2: __set__
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def __set__(self, instance, value):
if not self.related.field.rel.through._meta.auto_created:
opts = self.related.field.rel.through._meta
raise AttributeError(
"Cannot set values on a ManyToManyField which specifies an "
"intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
)
# Force evaluation of `value` in case it's a queryset whose
# value could be affected by `manager.clear()`. Refs #19816.
value = tuple(value)
manager = self.__get__(instance)
db = router.db_for_write(manager.through, instance=manager.instance)
with transaction.atomic(using=db, savepoint=False):
manager.clear()
manager.add(*value)
示例3: save
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def save(self, must_create=False):
"""
Save the current session data to the database. If 'must_create' is
True, raise a database error if the saving operation doesn't create a
new entry (as opposed to possibly updating an existing entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, force_update=not must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
except DatabaseError:
if not must_create:
raise UpdateError
raise
示例4: get_cascade_set
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def get_cascade_set(self, m):
""" Get the set of objects that would cascade if this object was
deleted.
"""
collector = XOSCollector(using=router.db_for_write(m.__class__, instance=m))
collector.collect([m])
deps = []
for (k, models) in collector.data.items():
for model in models:
if model == m:
# collector will return ourself; ignore it.
continue
if issubclass(m.__class__, model.__class__):
# collector will return our parent classes; ignore them.
continue
# We don't actually need this check, as with multiple passes the reaper can
# clean up a hierarchy of objects.
# if getattr(model, "backend_need_reap", False):
# # model is already marked for reaping; ignore it.
# continue
deps.append(model)
return deps
示例5: init_request
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
if django_version > (2, 1):
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.admin_site)
else:
(self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
示例6: get_deleted_objects
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def get_deleted_objects(objs, request, admin_site):
"""
Patched django/contrib/admin/utils.py
to skip collecting links for related nested objects
"""
try:
obj = objs[0]
except IndexError:
return [], {}, set(), []
else:
using = router.db_for_write(obj._meta.model)
collector = NestedObjects(using=using)
collector.collect(objs)
model_count = {model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items()}
to_delete = ['{}: {}'.format(cap_words(k), v) for k, v in model_count.items()]
return to_delete, model_count, None, None
示例7: get
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
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)))
示例8: save
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
示例9: set_many
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None):
exp = self.get_backend_timeout(timeout)
db = router.db_for_write(self.cache_model_class)
table = connections[db].ops.quote_name(self._table)
self._maybe_cull()
params = []
for key, value in data.items():
made_key = self.make_key(key, version=version)
self.validate_key(made_key)
value, value_type = self.encode(value)
params.extend((made_key, value, value_type, exp))
query = self._set_many_query.replace(
"{{VALUES_CLAUSE}}", ",".join("(%s, %s, %s, %s)" for key in data)
).format(table=table)
with connections[db].cursor() as cursor:
cursor.execute(query, params)
return []
示例10: _base_delta
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def _base_delta(self, key, delta, version, operation):
key = self.make_key(key, version=version)
self.validate_key(key)
db = router.db_for_write(self.cache_model_class)
table = connections[db].ops.quote_name(self._table)
with connections[db].cursor() as cursor:
updated = cursor.execute(
self._delta_query.format(table=table, operation=operation), (delta, key)
)
if not updated:
raise ValueError("Key '%s' not found, or not an integer" % key)
# New value stored in insert_id
return cursor.lastrowid
# Looks a bit tangled to turn the blob back into an int for updating, but
# it works. Stores the new value for insert_id() with LAST_INSERT_ID
示例11: delete_with_prefix
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def delete_with_prefix(self, prefix, version=None):
if version is None:
version = self.version
db = router.db_for_write(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:
return cursor.execute(
"""DELETE FROM {table}
WHERE cache_key LIKE %s""".format(
table=table
),
(prefix,),
)
示例12: save
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, force_update=not must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
except DatabaseError:
if not must_create:
raise UpdateError
raise
示例13: init_request
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def init_request(self, object_id, *args, **kwargs):
"The 'delete' admin view for this model."
self.obj = self.get_object(unquote(object_id))
if not self.has_delete_permission(self.obj):
raise PermissionDenied
if self.obj is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_str(self.opts.verbose_name), 'key': escape(object_id)})
using = router.db_for_write(self.model)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
(self.deleted_objects, self.model_count, self.perms_needed, self.protected) = get_deleted_objects(
[self.obj], self.opts, self.request.user, self.admin_site, using)
示例14: delete_without_cascade
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def delete_without_cascade(self, using=None, keep_parents=False):
"""
Modified version of django's default delete() method.
This method is added to enable safe deletion of the child models without
removing objects related to it through the parent. As of Feb 2017,
no models are directly related to the OAuth2DataRequestProject or
OnSiteDataRequestProject child models.
"""
allowed_models = [
"private_sharing.onsitedatarequestproject",
"private_sharing.oauth2datarequestproject",
]
if self._meta.label_lower not in allowed_models:
raise Exception("'delete_without_cascade' only for child models!")
using = using or router.db_for_write(self.__class__, instance=self)
assert self._get_pk_val() is not None, (
"%s object can't be deleted because its %s attribute is set to None."
% (self._meta.object_name, self._meta.pk.attname)
)
collector = Collector(using=using)
collector.collect([self], keep_parents=keep_parents, collect_related=False)
return collector.delete()
示例15: __set__
# 需要导入模块: from django.db import router [as 别名]
# 或者: from django.db.router import db_for_write [as 别名]
def __set__(self, instance, value):
# Force evaluation of `value` in case it's a queryset whose
# value could be affected by `manager.clear()`. Refs #19816.
value = tuple(value)
manager = self.__get__(instance)
db = router.db_for_write(manager.model, instance=manager.instance)
with transaction.atomic(using=db, savepoint=False):
manager.clear()
for obj in value:
manager.add(obj)