最大递归深度超过了getter Django

时间:2016-10-12 07:43:53

标签: python django recursion django-models attributes

我有一些针对特定attr的自定义getter的类:

class Item(a, b, c, d, models.Model):
     title = Field()
     description = Field()
     a = Field()
     _custom_getter = ['title','description']

     def __getattribute__(self, name):
         if name in self.custom_getter:
             return 'xxx'
         else:
             return super(Item, self).__getattribute__(name)

此代码引发RunetimeErrormaximum recursion depth exceeded while calling a Python object 但是当我使用这段代码时:

class Item(a, b, c, d, models.Model):
    title = Field()
    description = Field()
    a = Field()

    def __getattribute__(self, name):
        custom_getter = ['title','description']
        if name in custom_getter:
            return 'xxx'
        else:
            return super(Item, self).__getattribute__(name)

一切都像我想要的那样。第一段代码中我的错误是什么?

1 个答案:

答案 0 :(得分:3)

执行__getattribute__时会调用self.custom_getter。您可以使用self.__dict__。阅读更多How is the __getattribute__ method used?

class Item(a, b, c, d, models.Model):
     title = Field()
     description = Field()
     a = Field()
     custom_getter = ['title','description']

     def __getattribute__(self, name):
         if name in self.__dict__['custom_getter']:
             return 'xxx'
         else:
             return super(Item, self).__getattribute__(name)