我正在尝试使用以下代码在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
答案 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的超级...