0

我有一个模型:

class MyModel(models.Model):
    parent_content_type = models.ForeignKey(ContentType, related_name='prereq_parent')
    parent_object_id = models.PositiveIntegerField()
    parent_object = GenericForeignKey("parent_content_type", "parent_object_id")

    ...

    def get_parent(self):
       try:
           return self.parent_content_type.get_object_for_this_type(pk=self.parent_object_id)
       except ObjectDoesNotExist:
           #do something that will result in this instance of MyModel to be deleted

如果外键被删除,它会中断,所以当需要的外键被删除时,我不会中断,而是捕获它。发生这种情况时,如何删除整个 MyModel 实例,然后继续。

4

1 回答 1

0

在您删除外国课程之前:

foreign = ForeignClass.objects.get(pk=id)
myModel = MyModel.objects.filter(content_object=foreign)
myModel.delete()
foreign.delete()

希望这对你有用。

于 2015-08-31T07:49:28.013 回答