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(''))

but kept getting the error :

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))

  def fk1(cls):
      return Column(Integer, ForeignKey(''))
Share Comments
comments powered by Disqus