Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, as and bs, which have one column (id) but there is no a column in table bs that points to A.

What can I be doing wrong? My database is mysql, if it matters.

like image 521
flybywire Avatar asked Nov 17 '25 07:11

flybywire


1 Answers

relation() only tells the mapper how are the two tables related. You still need to add a column with the 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)
like image 166
Lukáš Lalinský Avatar answered Nov 18 '25 21:11

Lukáš Lalinský



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!