SQLalchemy not find table for creating foreign key
Although the top voted answer solves the issue, replacing strings with objects forces you to define tables in a specific order (which can be non-trivial for very large databases). From the SQLAlchemy docs:
The advantage to using a string is that the in-python linkage between [different tables] is resolved only when first needed, so that table objects can be easily spread across multiple modules and defined in any order.
You can continue to use strings by passing the schema to the ForeignKey
. For example, instead of doing:
tbl_estate_agent = Table(
'estate_agent', meta,
Column('person_id', Integer, ForeignKey("person.id"), primary_key = True),
Column('prize_range_id', Integer, ForeignKey("prize_range.id"), nullable = False),
schema = 'public')
One can do:
tbl_estate_agent = Table(
'estate_agent', meta,
Column('person_id', Integer, ForeignKey("public.person.id"), primary_key = True),
Column('prize_range_id', Integer, ForeignKey("public.prize_range.id"), nullable = False),
schema = 'public')
By adding the following line to my parent
table solved my problem. In case of Declarative:
children = relationship("Child")
Otherwise: SQLAlchemy - Classic Mapper
Also try to have a look in here (SO) too, might help.
In case of Declarative, I solved this problem by simply importing the class that was 'could not be found'.
The solution is to replace the strings with actual columns:
Column('person_id', Integer, ForeignKey(tbl_person.c.id), primary_key=True)