Python Django对象的递归删除外键
假设我有一个名为Person的对象,它有一个外键,链接到衣服,链接到Python Django对象的递归删除外键,python,django,recursion,Python,Django,Recursion,假设我有一个名为Person的对象,它有一个外键,链接到衣服,链接到 class Person(models.Model): clothes = models.ForeignKey('Clothes', on_delete=models.PROTECT) jokes = models.ManyToManyField(to='Jokes') class Clothes(models.Model): fabric = models.ForeignKey('Material'
class Person(models.Model):
clothes = models.ForeignKey('Clothes', on_delete=models.PROTECT)
jokes = models.ManyToManyField(to='Jokes')
class Clothes(models.Model):
fabric = models.ForeignKey('Material', on_delete=models.PROTECT)
class Material(models.Model):
plant = models.ForeignKey('Plant', on_delete=models.PROTECT)
如果我想删除这个人,我就必须删除衣服、笑话和附加的材料。是否有一种方法可以递归检测所有外键,以便我可以删除它们?django.db.models.deletation.Collector适合此任务。这就是Django在引擎盖下使用的级联删除 您可以这样使用它:
from django.db.models.deletion import Collector
collector = Collector(using='default') # You may specify another database
collector.collect([some_instance])
for model, instance in collector.instances_with_model():
# Our instance has already been deleted, trying again would result in an error
if instance == some_instance:
continue
instance.delete()
有关收集器
类的更多信息,请参考以下问题:
正如在评论中提到的,在_delete=models.CASCADE上使用
将是最好的解决方案,但如果您不能控制它,这应该会起作用。django.db.models.deletation.Collector
适合此任务。这就是Django在引擎盖下使用的级联删除
您可以这样使用它:
from django.db.models.deletion import Collector
collector = Collector(using='default') # You may specify another database
collector.collect([some_instance])
for model, instance in collector.instances_with_model():
# Our instance has already been deleted, trying again would result in an error
if instance == some_instance:
continue
instance.delete()
有关收集器
类的更多信息,请参考以下问题:
正如在评论中提到的,在_delete=models.CASCADE上使用,将是最好的解决方案,但如果您无法控制,这应该会起作用。为什么不在_delete=models.CASCADE上使用,代码库是由其他人编写的,我需要找到一种方法来覆盖删除信号上的。为什么不在删除=模型上使用。级联?我会的,但在这种情况下,代码库是由其他人编写的,我需要找到一种方法来覆盖删除信号上的。