I'm trying to create tables with foreign keys in database with peewee.
Player table has ForeignKey to Team table and Team table has ForeignKey to Player table. When i run my code i'm getting
NameError: name 'Team' is not defined
Here is my code:
class Player(Model):
nickname = CharField(max_length=30)
steam_id = CharField(max_length=15)
team = ForeignKeyField(Team)
class Meta:
database = db
class Team(Model):
name = CharField(max_length=30)
captain = ForeignKeyField(Player)
class Meta:
database = db
Player.create_table()
Team.create_table()
Can someone help me? :)
You're getting this error because you are referencing Team
in Player
, before you have defined Team
. You have a circular dependency here. Team
is dependent on Player
and Player
is dependent on Team
.
My first suggestion would be to drop one of the dependencies. Do you really need a reference to the other in both tables?
If you do, then the peewee docs has an entire section dedicated to handling this situation: http://peewee.readthedocs.org/en/latest/peewee/models.html#circular-foreign-key-dependencies