Django模型中的抽象继承,导致MAX递归深度错误 [英] Abstract Inheritance in Django Model, causing MAX recursion depth error
问题描述
我正在尝试使用以下代码在Django中实现抽象继承,但会产生MAX递归深度错误.我正在尝试覆盖模型的save
方法.
I'm trying to implement abstract inheritance in Django with the following code, but it produces a MAX recursion depth error. I'm trying to override a model's save
method.
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)
产生此错误(跟踪结束,很长):
produces this error (end of the trace, it's lengthy):
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
推荐答案
不要不要在self.__class__
上致电super
!在实际的课程上调用它:
Do not call super
on self.__class__
! Call it on the actual class:
return super(BaseModel, self).save(*args, **kwargs)
这是因为self.__class__
始终引用实例的实际具体类.因此,如果您从BaseModel
继承MyModel
,则当您进入BaseModel
中的save
方法时,self.__class__
仍然是MyModel
.因此,它将找到MyModel的超级对象,即BaseModel,因此调用BaseModel中的save,这将再次找到MyModel的超级对象...
This is because self.__class__
always refers to the actual concrete class of the instance. So if you inherit MyModel
from BaseModel
, when you get to the save
method in BaseModel
self.__class__
is still MyModel
. So it finds the super of MyModel, which is BaseModel, so calls the save in BaseModel, which once again finds the super of MyModel...
这篇关于Django模型中的抽象继承,导致MAX递归深度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!