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

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

but kept getting the error :

1
2
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 :

1
2
3
4
5
6
class MyBase(Base):
  name = Column(String(30))

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