Django モデルの 1 つにこの奇妙な問題があり、修正できましたが、何が起こっているのかわかりません。
これらはモデルです:
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...
代わりに、理解できない再帰が発生します。