[Python] SQLAlchemy error when creating table with foreign key

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have three tables, with one table having a foreign key referencing another.

    Table Appearance:

    class Appearance(Base):
    __tablename__ = 'appearances'
    appearance_id = Column(Integer, primary_key=True)
    game_id = Column(Integer, nullable=False)
    player_id = Column(Integer, nullable=False)


    Table Club

    class Club(Base):
    __tablename__ = 'clubs'

    club_id = Column(Integer, primary_key=True)
    club_code = Column(String(50))
    name = Column(String(100), nullable=False)


    And finally the last table with foreign key: Table Player

    class Player(Base):
    __tablename__ = 'players'

    player_id = Column(Integer, primary_key=True)
    first_name = Column(String(100))
    current_club_id = Column(Integer, ForeignKey('clubs.club_id'))


    The Club and Appearance tables are created without any error on database, I can see them, but the Players table is not created because I get an error on foreign key:

    Foreign key associated with column 'players.current_club_id' could not find table 'clubs' with which to generate a foreign key to target column 'club_id'


    But I can see the table club exist on database!!

    to create table I have this

    def create_tables(engine):

    tables = [
    Appearance,
    Club,
    Player
    ]

    for table in tables:
    try:
    table.__table__.create(engine)
    print(f"Table {table.__tablename__} success!")
    except Exception as e:
    print(f"error with table {table.__tablename__}: {e}")


    What is the problem here?

    Continue reading...

Compartilhe esta Página