Briefly
From a model other than the author
author_id = db.Column(db.Integer, db.ForeignKey(Author.__table__.c.id))
From the authorβs model itself, i.e. self-referential - just list the column name
author_id = db.Column(db.Integer, db.ForeignKey(id))
CANNOT use string value
author_id = db.Column(db.Integer, db.ForeignKey('Author.id'))
Full information
ForeignKey takes a column as the first argument, which can be of type Column or a string in the format schema_name.table_name.column_name or table_name.column_name . The columns that you define in the declarative model refer to InstumentedAttribute objects. This is why db.ForeignKey(Author.id) leads to an error. You can access the actual column using the __table__ attribute of the model:
author_id = db.Column(db.Integer, db.ForeignKey(Author.__table__.c['id']))
or
author_id = db.Column(db.Integer, db.ForeignKey(Author.__table__.c.id))
If you need to define a foreign key for a self-referencing, you can simply pass the column name. While the model declaration is not yet complete, it still has a Column type:
id = db.Column(db.Integer, primary_key=True) parent_id = db.Column(db.Integer, db.ForeignKey(id))
Note that you CANNOT define a foreign key as follows:
author_id = db.Column(db.Integer, db.ForeignKey('Author.id'))
You need to specify the physical name of the table, the name of the mapping class will not work.
Sergey Shubin
source share