问题描述
虽然我知道如何使用它,并且搜索了比较我的代码的例子,但是我无法得到为什么我不能调用一个模型,它有它的 __ str __
__ STR __
。我得到一个 RuntimeError:__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)
好的,我设法知道发生了什么。这是因为装饰器 python_2_unicode_compatible (来自django.utils.encoding import python_2_unicode_compatible 的)。以下是问题开始的追溯:
/ my / path / to / django / utils / six in< lambda )
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。这就是你以递归的方式去eminity!and beyond!。删除装饰器并将类方法更改为 __ unicode __
可以解决问题。
编辑
保留装饰器的一种替代方法是在父项中添加自定义方法:
code> def str(self):
returnfoo
def __str __(self):
return self.str()
然后在孩子中你只要执行 self.str()
/ p>
Although I know how to make it, and have searched examples for comparing my code, I cannot get why I cannot call a model that has its __str__
calling inside its parent's __str__
. I get a RuntimeError: maximum recursion depth exceeded in __subclasscheck__
, which should not be happening.
Here is my code below. No collateral work that could be affecting it:
@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)
Ok, I managed to know what was happening. It was because of the decorator python_2_unicode_compatible (from django.utils.encoding import python_2_unicode_compatible
). Here's the traceback where problem starts:
/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
So, the decorator assigns __str__
to __unicode__
, then assigns to __str__
a lambda which calls __unicode__
(circular dependency). And that's how you go to "Infinity! And beyond!" in recursion terms. Deleting the decorator and changing the class methods to __unicode__
solves the problem.
EDIT
An alternative to keep the decorator would be adding a custom method in the parent:
def str(self):
return "foo"
def __str__(self):
return self.str()
Then in the child you just do self.str()
also.
这篇关于在Django中无法自定义__str__调用父代的__str__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!