我有一个模型:
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 实例,然后继续。