模型定义:订购Importo避免ImportError

时间:2011-03-19 01:01:12

标签: python django models

无法让我的所有导入正常运行。他们在定义之前互相打电话。

match.models:

from player.models import Player

class Match(models.Model):
    player = models.ForeignKey(Player)

player.models:

class Player(models.Model):
    #yadda yadda

from match.models import Match
class Skill(models.Model):
    player = ForeignKey(Player)
    match = ForeignKey(Match)

这都是糖果苹果,工作正常。但后来我想为播放器添加模型方法:

class Player(models.Model):
    def get_skill():
        skill = Skill.objects.filter()

现在,技能未在播放器之前定义。移动技能以在播放器之前定义它(因此在其之前导入匹配)会中断匹配,因为它必须导入播放器尚未定义。

File "...match/models.py", line 2, in <module>
    from player.models import Player
ImportError: cannot import name Player

你明白了。

我真的很想保留模型方法,我对使所有导入工作无能为力。我想我可以将技能从玩家模式中移除到自己的模式中,但这将是一个令人头疼的问题,我想知道如何正确地做到这一点。

1 个答案:

答案 0 :(得分:2)

Lazy Relationships

匹配models.py

class Match(models.Model):
    player = models.ForeignKey('player.Player')

播放器models.py

class Skill(models.Model):
    player = ForeignKey('Player')
    match = ForeignKey('match.Match')

class Player(models.Model):
    #yadda yadda

    def get_skill():
       skill = Skill.object.filter()