I'm new to sqlalchemy. I have followed the tutorial to create the automap of a existing db with relationship from a mysql db
from sqlalchemy import create_engine, MetaData, Column, Table, ForeignKey
from sqlalchemy.ext.automap import automap_base, generate_relationship
from sqlalchemy.orm import relationship, backref
from config import constr, mytables
def _gen_relationship(base, direction, return_fn,
attrname, local_cls, refferred_cls, **kw):
return generate_relationship(base, direction, return_fn, attrname, local_cls, refferred_cls, **kw)
engine = create_engine(constr)
metadata = MetaData()
metadata.reflect(engine, only=mytables)
Base = automap_base(metadata=metadata)
Base.prepare(engine, reflect=True, generate_relationship=_gen_relationship)
Tableclass1 = Base.classes.table1
Tableclass2 = Base.classes.table2
Table2.ID
maps to one of table1
's columns. But when I was trying to use query and join table1
and table2
, it reports error saying that "Can't find any foreign key relationships". Since I know the relationship of these 2 tables, is there way for me the declare this relationship after the class instance has been created? Or is there way to explicitly tell this relationship in query function?
Thanks!