Using ForeignKey in Abstract Base Class (SQLAlchemy)

I was creating an abstract base class containing FK, like this :

class MyBase(Base):
  name = Column(String(30))
  fk1 = Column(Integer, ForeignKey('table1.id'))

but kept getting the error :

sqlalchemy.exc.InvalidRequestError:
Columns with foreign keys to other columns must be declared as @declared_attr callables on declarative mixin classes.

Reading thru the docs was not helpful because the example used for @declared_attr is somewhat different

this SO answer helped.

Essentially use it as :

class MyBase(Base):
  name = Column(String(30))

  @declared_attr
  def fk1(cls):
      return Column(Integer, ForeignKey('table1.id'))

Comments

Comments powered by Disqus
Google Analytics Alternative