Ticket #13513: collect_sub_objects.patch

File collect_sub_objects.patch, 2.5 KB (added by gavoja, 5 years ago)

Proposed patch.

  • db/models/base.py

     
    544544
    545545    save_base.alters_data = True
    546546
    547     def _collect_sub_objects(self, seen_objs, parent=None, nullable=False):
     547    def _collect_sub_objects(self, seen_objs, using=None, parent=None, nullable=False):
    548548        """
    549549        Recursively populates seen_objs with all objects related to this
    550550        object.
     
    553553            [(model_class, {pk_val: obj, pk_val: obj, ...}),
    554554             (model_class, {pk_val: obj, pk_val: obj, ...}), ...]
    555555        """
     556        using = using or router.db_for_write(self.__class__, instance=self)
     557
    556558        pk_val = self._get_pk_val()
    557559        if seen_objs.add(self.__class__, pk_val, self,
    558560                         type(parent), parent, nullable):
     
    592594                reverse_field_name = related.field.m2m_reverse_field_name()
    593595                nullable = opts.get_field(reverse_field_name).null
    594596                filters = {reverse_field_name: self}
    595                 for sub_obj in related.field.rel.through._base_manager.filter(**filters):
     597                for sub_obj in related.field.rel.through._base_manager.using(using).filter(**filters):
    596598                    sub_obj._collect_sub_objects(seen_objs, self, nullable)
    597599
    598600        for f in self._meta.many_to_many:
     
    601603                field_name = f.m2m_field_name()
    602604                nullable = opts.get_field(field_name).null
    603605                filters = {field_name: self}
    604                 for sub_obj in f.rel.through._base_manager.filter(**filters):
     606                for sub_obj in f.rel.through._base_manager.using(using).filter(**filters):
    605607                    sub_obj._collect_sub_objects(seen_objs, self, nullable)
    606608            else:
    607609                # m2m-ish but with no through table? GenericRelation: cascade delete
     
    627629
    628630    def delete(self, using=None):
    629631        using = using or router.db_for_write(self.__class__, instance=self)
    630         connection = connections[using]
     632
    631633        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)
    632634
    633635        # Find all the objects than need to be deleted.
    634636        seen_objs = CollectedObjects()
    635         self._collect_sub_objects(seen_objs)
     637        self._collect_sub_objects(seen_objs, using)
    636638
    637639        # Actually delete the objects.
    638640        delete_objects(seen_objs, using)
Back to Top