Django模型中的抽象继承,导致MAX递归深度误差

时间:2012-06-08 11:39:39

标签: django inheritance recursion depth

我正在尝试使用以下代码在Django中实现抽象继承,但它会产生MAX递归深度错误。我正在尝试覆盖模型的save方法。

class BaseModel(models.Model):
    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        #i'm doing something here

        #i think the problem is in the return statement specifically because of the
        #self.__class__ expression.
        return super(self.__class__, self).save(*args, **kwargs)

class MyModel(BaseModel):
    p = models.CharField(max_length=30)

产生此错误(跟踪结束,它很长):

  File "/home/jultra/ap3w/jultra_01/mysite/testsite/models.py", line 10, in save
    return super(self.__class__, self).save(*args, **kwargs)
  File "/home/jultra/ap3w/jultra_01/mysite/testsite/models.py", line 10, in save
    return super(self.__class__, self).save(*args, **kwargs)
  File "/home/jultra/ap3w/jultra_01/mysite/testsite/models.py", line 10, in save
    return super(self.__class__, self).save(*args, **kwargs)
  File "/home/jultra/ap3w/jultra_01/mysite/testsite/models.py", line 10, in save
    return super(self.__class__, self).save(*args, **kwargs)
RuntimeError: maximum recursion depth exceeded

1 个答案:

答案 0 :(得分:13)

super上拨打self.__class__!在实际课程上调用它:

return super(BaseModel, self).save(*args, **kwargs)

这是因为self.__class__总是引用实例的实际具体类。因此,如果您从MyModel继承BaseModel,那么当您save BaseModel中的self.__class__方法仍然是MyModel时。所以它找到MyModel的超级,它是BaseModel,所以在BaseModel中调用save,它再次找到了MyModel的超级...