Python django.db.models.deletion.Collector() Examples

The following are 22 code examples of django.db.models.deletion.Collector(). 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.models.deletion , or try the search function .
Example #1
Source File: query.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def delete(self):
        """
        Deletes the records in the current QuerySet.
        """
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        del_query = self._clone()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None 
Example #2
Source File: models.py    From open-humans with MIT License 6 votes vote down vote up
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 #3
Source File: query.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def delete(self):
        """
        Deletes the records in the current QuerySet.
        """
        assert self.query.can_filter(), \
                "Cannot use 'limit' or 'offset' with delete."

        del_query = self._clone()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None 
Example #4
Source File: xosbase_header.py    From xos with Apache License 2.0 6 votes vote down vote up
def setup_simple_attributes(cls):
        for (attrname, default) in cls.simple_attributes:
            setattr(
                cls,
                attrname,
                property(
                    lambda self, attrname=attrname, default=default: self.get_attribute(
                        attrname, default
                    ),
                    lambda self, value, attrname=attrname: self.set_attribute(
                        attrname, value
                    ),
                    None,
                    attrname,
                ),
            )


# For cascading deletes, we need a Collector that doesn't do fastdelete,
# so we get a full list of models. 
Example #5
Source File: xosbase_header.py    From xos with Apache License 2.0 6 votes vote down vote up
def setup_simple_attributes(cls):
        for (attrname, default) in cls.simple_attributes:
            setattr(
                cls,
                attrname,
                property(
                    lambda self, attrname=attrname, default=default: self.get_attribute(
                        attrname, default
                    ),
                    lambda self, value, attrname=attrname: self.set_attribute(
                        attrname, value
                    ),
                    None,
                    attrname,
                ),
            )


# For cascading deletes, we need a Collector that doesn't do fastdelete,
# so we get a full list of models. 
Example #6
Source File: BaseModel.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
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 #7
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def delete(self, using=None):
        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])
        collector.delete() 
Example #8
Source File: server.py    From hawthorne with GNU Lesser General Public License v3.0 5 votes vote down vote up
def modal_delete(request, s, *args, **kwargs):
  server = Server.objects.get(id=s)

  collector = Collector(using='default')
  collector.collect([server])
  estimate = sum(len(x) for x in collector.data.values())

  breakdown = {}
  for k, v in collector.data.items():
    name = k._meta.verbose_name_plural if len(v) != 1 else k._meta.verbose_name
    breakdown[name] = len(v)

  return render(request, 'components/servers/detailed/modals/delete.pug',
                {'estimate': estimate,
                 'breakdown': breakdown}) 
Example #9
Source File: query.py    From python2017 with MIT License 5 votes vote down vote up
def delete(self):
        """
        Deletes the records in the current QuerySet.
        """
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        if self._fields is not None:
            raise TypeError("Cannot call delete() after .values() or .values_list()")

        del_query = self._clone()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        deleted, _rows_count = collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
        return deleted, _rows_count 
Example #10
Source File: base.py    From python2017 with MIT License 5 votes vote down vote up
def delete(self, using=None, keep_parents=False):
        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)
        return collector.delete() 
Example #11
Source File: query.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def delete(self):
        """
        Deletes the records in the current QuerySet.
        """
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        if self._fields is not None:
            raise TypeError("Cannot call delete() after .values() or .values_list()")

        del_query = self._clone()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        deleted, _rows_count = collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
        return deleted, _rows_count 
Example #12
Source File: base.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def delete(self, using=None, keep_parents=False):
        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)
        return collector.delete() 
Example #13
Source File: operations.py    From django-more with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def as_sql(self):
        """ Generate SQL queries that perform related deletion """
        # List of (sql, params) tuples to perform deletion
        query_list = []

        for model, instances in self.data.items():
            self.data[model] = sorted(instances, key=attrgetter("pk"))
        self.sort()
        # Do not send pre_delete signals as in .delete()

        # Fast deletes
        for qs in self.fast_deletes:
            # TODO Check for any potential caveats from complex queries - assume none are generated by Collector

            # Clone queryset into DeleteQuery to use .as_sql()
            query_list.append(qs.query.clone(klass=sql.DeleteQuery).get_compiler(self.using).as_sql())

        # update fields
        for model, instances_for_fieldvalues in six.iteritems(self.field_updates):
            query = sql.UpdateQuery(model)
            for (field, value), instances in six.iteritems(instances_for_fieldvalues):
                query.add_update_values({field.name: value})
                query.add_q(models.Q(pk__in=[obj.pk for obj in instances]))
                query_list.append(query.get_compiler(using=self.using).as_sql())

        # reverse instance collections
        for instances in six.itervalues(self.data):
            instances.reverse()

        # delete instances
        for model, instances in six.iteritems(self.data):
            query = sql.DeleteQuery(model)
            pk_list = [obj.pk for obj in instances]
            query.where = query.where_class()
            query.add_q(models.Q(pk__in=pk_list))
            query_list.append(query.get_compiler(using=self.using).as_sql())

        # Do not update instances as in .delete()
        return query_list 
Example #14
Source File: base.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def delete(self, using=None):
        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])
        collector.delete() 
Example #15
Source File: base.py    From django2-project-template with MIT License 5 votes vote down vote up
def _collect_related(self, using=None, keep_parents=False):
        collector = Collector(using=using)
        collector.collect([self], keep_parents=keep_parents)
        fast_deletes = []
        for queryset in collector.fast_deletes:
            if queryset.count() > 0:
                fast_deletes.append(queryset)

        return dict(
            instances_with_model=collector.instances_with_model(), fast_deletes=fast_deletes, data=collector.data
        ) 
Example #16
Source File: query.py    From python with Apache License 2.0 5 votes vote down vote up
def delete(self):
        """
        Deletes the records in the current QuerySet.
        """
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        if self._fields is not None:
            raise TypeError("Cannot call delete() after .values() or .values_list()")

        del_query = self._clone()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        deleted, _rows_count = collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
        return deleted, _rows_count 
Example #17
Source File: base.py    From python with Apache License 2.0 5 votes vote down vote up
def delete(self, using=None, keep_parents=False):
        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)
        return collector.delete() 
Example #18
Source File: query.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def delete(self):
        """Delete the records in the current QuerySet."""
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        if self._fields is not None:
            raise TypeError("Cannot call delete() after .values() or .values_list()")

        del_query = self._chain()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        deleted, _rows_count = collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
        return deleted, _rows_count 
Example #19
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def delete(self, using=None, keep_parents=False):
        using = using or router.db_for_write(self.__class__, instance=self)
        assert self.pk 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)
        return collector.delete() 
Example #20
Source File: finddupemail.py    From website with GNU General Public License v3.0 5 votes vote down vote up
def get_cascades(self, user):
        c = Collector(user._state.db)
        c.collect([user])

        # figure out which models this user has data in
        existing = set(c.data.keys())
        existing.update(q.model for q in c.fast_deletes if q.exists())
        # but don't mention they have a User, that's obvious:
        existing.discard(User)
        return existing 
Example #21
Source File: base.py    From bioforum with MIT License 5 votes vote down vote up
def delete(self, using=None, keep_parents=False):
        using = using or router.db_for_write(self.__class__, instance=self)
        assert self.pk 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)
        return collector.delete() 
Example #22
Source File: query.py    From bioforum with MIT License 5 votes vote down vote up
def delete(self):
        """Delete the records in the current QuerySet."""
        assert self.query.can_filter(), \
            "Cannot use 'limit' or 'offset' with delete."

        if self._fields is not None:
            raise TypeError("Cannot call delete() after .values() or .values_list()")

        del_query = self._chain()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._for_write = True

        # Disable non-supported fields.
        del_query.query.select_for_update = False
        del_query.query.select_related = False
        del_query.query.clear_ordering(force_empty=True)

        collector = Collector(using=del_query.db)
        collector.collect(del_query)
        deleted, _rows_count = collector.delete()

        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
        return deleted, _rows_count