使用这样的嵌套模型:
class Gov(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class State(models.Model):
parent = models.ForeignKey(Gov)
abbreviation = models.CharField(max_length=100)
def __str__(self):
return self.parent.name
class State_Park(models.Model):
parent = models.ForeignKey(State)
park_name = models.CharField(max_length=100)
如何将__str__
State_Park
name
设为class Gov
中的def __str__(self):
return self.parent.parent.name
?
我试过了:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\ccsv\Envs\wenv\lib\site-packages\django\db\models\query.py", line 229, in __repr__
return '<%s %r>' % (self.__class__.__name__, data)
File "C:\Users\ccsv\Envs\wenv\lib\site-packages\django\db\models\base.py", line 589, in __repr__
u = six.text_type(self)
File "C:\Users\ccsv\Desktop\wenv\mysite\stats\models.py", line 89, in __str__
return self.parent.parent.name()
TypeError: 'str' object is not callable
哪个不起作用。
{{1}}
答案 0 :(得分:4)
是
return self.parent.parent.name()
只需删除括号
return self.parent.parent.name
# ^^^
答案 1 :(得分:3)
File "C:\Users\ccsv\Desktop\wenv\mysite\stats\models.py", line 89, in __str__
return self.parent.parent.name()
根据错误日志,我认为您应该删除行尾的括号。
def __str__(self):
return self.parent.parent.name