我在Django模型中遇到一个奇怪的问题,虽然已经修复了,但是不明白发生了什么。
以下是这些模型:
class Player(models.Model):
facebook_name = models.CharField(max_length=100)
nickname = models.CharField(max_length=40, blank=True)
def __unicode__(self):
return self.nickname if self.nickname else self.facebook_name
class Team(models.Model):
name = models.CharField(max_length=50, blank=True)
players = models.ManyToManyField(Player)
def __unicode__(self):
name = '(' + self.name + ') ' if self.name else ''
return name + ", ".join([unicode(player) for player in self.players.all()])
每当我创建一个新的(空的)Team
对象并想要从中获取players
时,我会得到一个RuntimeError: maximum recursion depth exceeded
错误。
例如:>>> team = Team()
>>> team.players
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/walkman/Projects/fociadmin/venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 897, in __get__
through=self.field.rel.through,
File "/Users/walkman/Projects/fociadmin/venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 586, in __init__
(instance, source_field_name))
File "/Users/walkman/Projects/fociadmin/venv/lib/python2.7/site-packages/django/db/models/base.py", line 421, in __repr__
u = six.text_type(self)
File "/Users/walkman/Projects/fociadmin/fociadmin/models.py", line 69, in __unicode__
return name + ", ".join([unicode(player) for player in self.players.all()])
File "/Users/walkman/Projects/fociadmin/venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 897, in __get__
through=self.field.rel.through,
File "/Users/walkman/Projects/fociadmin/venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 586, in __init__
(instance, source_field_name))
File "/Users/walkman/Projects/fociadmin/venv/lib/python2.7/site-packages/django/db/models/base.py", line 421, in __repr__
u = six.text_type(self)
File "/Users/walkman/Projects/fociadmin/fociadmin/models.py", line 69, in __unicode__
return name + ", ".join([unicode(player) for player in self.players.all()])
...
为什么会发生这种情况?我通过检查pk
并仅在此时生成名称来解决了它,但我认为它应该只返回名称,因为", ".join...
将成为空列表。相反,发生了一些我不理解的递归。
ValueError
并导致所描述的情况。如果该实例已保存(并具有主键),则关系将是一个空列表。 - AndrewS