简体   繁体   中英

Two tables with foreign key referencing the other, NameError

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

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

So for

team = ForeignKeyField(Team)

use

team = DeferredForeignKeyField('Team')

and then later

db.create_tables([Player,Team])
Player._schema.create_foreign_key(Player.team)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM