递归删除Django对象的外键

时间:2017-01-04 16:16:21

标签: python django recursion

假设我有一个名为Person的对象,它有一个链接到链接到

的CLothes的外键
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)

如果我想删除人,我将不得不删除附加的衣服,笑话,材料。有没有办法递归检测所有外键,以便我可以删除它们?

1 个答案:

答案 0 :(得分:2)

django.db.models.deletion.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()

有关Collector课程的详细信息,请参阅此问题:

How to show related items using DeleteView in Django?

正如评论中所提到的,使用on_delete=models.CASCADE将是最佳解决方案,但如果您无法控制,那么这应该可行。