Sqlalchemy does not create my foreign key

SqlAlchemy newbie question:

Base = declarative_base()

class A(Base):
    __tablename__ = 'as'
    id = Column(Integer, primary_key=True)

class B(Base):
    __tablename__ = 'bs'
    id = Column(Integer, primary_key=True)
    a = relation(A)

When I create my database schema, I have two tables: and bs, which have one column (id), but there is no column in table bs athat points to A.

What can i do wrong? My database is mysql, if that matters.

+3
source share
1 answer

relation()only indicates how the two tables are matched. You still need to add a column with foreign key information. For example:

class B(Base):
    __tablename__ = 'bs'
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('as.id'), name="a")
    a = relation(A)
+5
source

Source: https://habr.com/ru/post/1724318/


All Articles