无法在Django中自定义__str__调用parent的__str__

时间:2017-03-08 10:54:53

标签: django python-2.7

虽然我知道如何制作它,并搜索了比较我的代码的示例,但我无法理解为什么我不能在其父__str__内调用其__str__调用的模型。我得到RuntimeError: maximum recursion depth exceeded in __subclasscheck__ ,这不应该发生。

以下是我的代码。没有可能影响它的抵押品工作:

@python_2_unicode_compatible
class A(models.Model):
    def __str__(self):
        return self.attr

@python_2_unicode_compatible
class B(A):
    def __str__(self):
        return "%s - %s" % (super(B, self).__str__(), self.attr_two)

2 个答案:

答案 0 :(得分:2)

好的,我设法知道发生了什么。这是因为装饰者 python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible)。这是问题开始的追溯:

/my/path/to/django/utils/six in <lambda>(self)
    840                              klass.__name__)
    841         klass.__unicode__ = klass.__str__
--> 842         klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
    843     return klass
    844

因此,装饰者将__str__分配给__unicode__,然后将__str__分配给调用__unicode__的lambda(循环依赖)。这就是你如何以递归术语去“无限!超越!”。删除装饰器并将类方法更改为__unicode__可以解决问题。

修改

保持装饰器的替代方法是在父级中添加自定义方法:

def str(self):
    return "foo"

def __str__(self):
    return self.str()

然后在孩子中你也self.str()

答案 1 :(得分:0)

每个对象

__str__,而不是每个类。所以,你会这样做:

class B(A):

    def __str__(self):
        return "%s - %s" % (self.attr, self.attr_two)