Python django.db.router.db_for_write() Examples
The following are 30
code examples of django.db.router.db_for_write().
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: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 6 votes |
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,), )
Example #2
Source File: related.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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)
Example #3
Source File: models.py From open-humans with MIT License | 6 votes |
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()
Example #4
Source File: db.py From bioforum with MIT License | 6 votes |
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
Example #5
Source File: related.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def __set__(self, instance, value): if not self.field.rel.through._meta.auto_created: opts = self.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)
Example #6
Source File: reaper.py From xos with Apache License 2.0 | 6 votes |
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
Example #7
Source File: delete.py From weibo-analysis-system with MIT License | 6 votes |
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)
Example #8
Source File: reaper.py From xos with Apache License 2.0 | 6 votes |
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
Example #9
Source File: delete.py From myblog with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #10
Source File: delete.py From CTF_AWD_Platform with MIT License | 6 votes |
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)
Example #11
Source File: delete.py From devops with MIT License | 6 votes |
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)
Example #12
Source File: delete.py From imoocc with GNU General Public License v2.0 | 6 votes |
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)
Example #13
Source File: delete.py From django_OA with GNU General Public License v3.0 | 6 votes |
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)
Example #14
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #15
Source File: cache.py From django-mysql with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 []
Example #16
Source File: delete.py From Mxonline3 with Apache License 2.0 | 6 votes |
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)
Example #17
Source File: db.py From openhgsenti with Apache License 2.0 | 6 votes |
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
Example #18
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 #19
Source File: delete.py From StormOnline with Apache License 2.0 | 6 votes |
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)
Example #20
Source File: db.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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
Example #21
Source File: db.py From python2017 with MIT License | 6 votes |
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
Example #22
Source File: admin.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 6 votes |
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
Example #23
Source File: db.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def clear(self): db = router.db_for_write(self.cache_model_class) table = connections[db].ops.quote_name(self._table) cursor = connections[db].cursor() cursor.execute('DELETE FROM %s' % table) # For backwards compatibility
Example #24
Source File: related.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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): # If the foreign key can support nulls, then completely clear the related set. # Otherwise, just move the named objects into the set. if self.related.field.null: manager.clear() manager.add(*value)
Example #25
Source File: options.py From python2017 with MIT License | 5 votes |
def changeform_view(self, request, object_id=None, form_url='', extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context)
Example #26
Source File: options.py From python2017 with MIT License | 5 votes |
def delete_view(self, request, object_id, extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._delete_view(request, object_id, extra_context)
Example #27
Source File: BaseModel.py From GloboNetworkAPI with Apache License 2.0 | 5 votes |
def delete(self, *args, **kwargs): """ Replace super(BaseModel, self).delete() Cause: When delete relationship in cascade default no have attribute User to Log. """ using = 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]) collector.delete()
Example #28
Source File: options.py From python with Apache License 2.0 | 5 votes |
def changeform_view(self, request, object_id=None, form_url='', extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context)
Example #29
Source File: options.py From python with Apache License 2.0 | 5 votes |
def delete_view(self, request, object_id, extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._delete_view(request, object_id, extra_context)
Example #30
Source File: related.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name) # The similarity of the code below to the code in # ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch # of small differences that would make a common base class convoluted. # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.related.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.related.get_accessor_name())) elif value is not None and not isinstance(value, self.related.model): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.related.get_accessor_name(), self.related.opts.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) related_pk = getattr(instance, self.related.field.rel.get_related_field().attname) if related_pk is None: raise ValueError('Cannot assign "%r": "%s" instance isn\'t saved in the database.' % (value, instance._meta.object_name)) # Set the value of the related field to the value of the related object's related field setattr(value, self.related.field.attname, related_pk) # Since we already know what the related object is, seed the related # object caches now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.cache_name, value) setattr(value, self.related.field.get_cache_name(), instance)