[英]Two tables with foreign key referencing the other, NameError
I'm trying to create tables with foreign keys in database with peewee. 我正在尝试使用peewee在数据库中使用外键创建表。
Player table has ForeignKey to Team table and Team table has ForeignKey to Player table. 玩家表具有对团队表的ForeignKey,而团队表具有对玩家表的ForeignKey。 When i run my code i'm getting NameError: name 'Team' is not defined
当我运行代码时,我收到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
. 你得到这个错误,因为你引用Team
中Player
,你定义了前Team
。 You have a circular dependency here. 您在这里有一个循环依赖性。 Team
is dependent on Player
and Player
is dependent on Team
. Team
取决于Player
而Player
则取决于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 如果您这样做,则peewee文档中有专门的章节专门处理这种情况: http ://peewee.readthedocs.org/en/latest/peewee/models.html#circular-foreign-key-dependencies
You need to use DeferredForeignKey this uses the Django style type-as-string approach, but comes with the caveat it won't create your database constraints for you 您需要使用DeferredForeignKey,它使用Django样式的字符串输入法,但附带说明它不会为您创建数据库约束
So for 因此对于
team = ForeignKeyField(Team)
use 采用
team = DeferredForeignKeyField('Team')
and then later 然后再
db.create_tables([Player,Team])
Player._schema.create_foreign_key(Player.team)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.