开发者

Model Definitions: Ordering Importo Avoid ImportError

开发者 https://www.devze.com 2023-02-18 14:42 出处:网络
Having trouble getting all of my imports working correctly. They\'re calling each other before they\'re defined.

Having trouble getting all of my imports working correctly. They're calling each other before they're defined.

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)

That's all candy apples, works fine. But then I wanted to add a model method to Player:

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

Now, Skill is not defined before the player. Moving Skill to have it defined before Player (and therefore importing match ahead of it) breaks Match, because it has to import Player which isn't defined yet.

File "...match/models.py", line 2, in <module>
    from player.models import Player
ImportError: cannot import n开发者_如何学Pythoname Player

You get the idea.

I'd really like to keep the model method, I'm just clueless about making all the imports work. I guess I could pull Skill out of player.models into its own, but that will be a headache at this point and I'd like to know how to do it properly.


Lazy Relationships

match models.py

class Match(models.Model):
    player = models.ForeignKey('player.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()
0

精彩评论

暂无评论...
验证码 换一张
取 消