摘要继承在Django模型,引起MAX递归深度误差(Abstract Inheritance in

2019-09-17 22:37发布

我想实现Django中抽象继承与下面的代码,但它会产生一个最大递归深度误差。 我试图重写一个模型的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

Answer 1:

不要superself.__class__ ! 调用它的实际类:

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

这是因为self.__class__总是指实际的具体类的实例。 所以,如果你继承MyModelBaseModel ,当你到了save在方法BaseModel self.__class__仍然是MyModel 。 所以发现为MyModel,这是BaseModel的超级,所以调用BaseModel,这再次发现为MyModel的超级救...



文章来源: Abstract Inheritance in Django Model, causing MAX recursion depth error