我是 sqlalchemy 的新手。我已按照教程创建与 mysql 数据库有关系的现有数据库的自动映射
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
映射到table1
's 列之一。但是当我尝试使用 query 和 join table1
andtable2
时,它报告错误说“找不到任何外键关系”。既然我知道这两个表的关系,我有没有办法在创建类实例后声明这种关系?或者有没有办法在查询函数中明确地告诉这种关系?谢谢!