带自定义模型删除方法的级联删除

带自定义模型删除方法的级联删除

本文介绍了带自定义模型删除方法的级联删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型上有一个自定义的删除方法,确保在调用<$ c时可以正确调用通过使用以下命令在QuerySet上删除$ c> :

I have a custom delete method on my Model that I make sure is called correctly when calling delete on the QuerySet by using:Custom delete method on queryset.

当Django执行级联删除时,这似乎不起作用。在那种情况下,ORM在常规的 QuerySet 上调用 _raw_delete ,从而绕过我的自定义删除方法。

This does not seem to work when Django performs a cascading delete. In that case, the ORM calls _raw_delete on a regular QuerySet thereby bypassing my custom delete method.

如何防止这种情况发生?

How do I prevent that from happening?

问题似乎是由于使用了 _base_manager 而不是 _default_manager

The issue seems to be caused because this uses _base_manager rather than _default_manager:

def related_objects(self, related, objs):
  return related.related_model._base_manager.using(self.using).filter(
      **{"%s__in" % related.field.name: objs}
  )


推荐答案

似乎我需要将此添加到 QuerySet

It looks like I need to add this to the QuerySet:

 def _raw_delete(self, using):
        self.delete()
    _raw_delete.alters_data = True

并设置 use_for_related_fields = True Manager 上。

这篇关于带自定义模型删除方法的级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:14