我是sqlalchemy的新手。我已经按照教程创建了一个与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
映射到table1
个列之一。但是,当我尝试使用查询并加入table1
和table2
时,它会报告错误,说“"无法找到任何外键关系"”。既然我知道了这两个表的关系,那么在创建类实例之后是否可以声明这种关系?或者有没有办法在查询功能中明确告诉这种关系?
谢谢!
答案 0 :(得分:2)
虽然可以在@mpolednik提到的查询中执行此操作,但如果我正确地阅读了您的问题,理想的解决方案是在您的类中声明关系以供重复使用。
可以通过预先声明您想要使用的类来实现,如下所示:
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session, relationship
from sqlalchemy import create_engine, Column, String
Base = automap_base()
engine = create_engine("postgresql://user:pass@localhost:5432/mydb")
# pre-declare User for the 'user' table
class User(Base):
__tablename__ = 'user'
# override schema elements like Columns
oname = Column('originalname', String)
# and a relationship. I name it 'weird' because in my database schema
# this relationship makes absolutely no sense, but it does demonstrate
# the point
weird = relationship("usergroup",
foreign_keys='usergroup.id',
primaryjoin='and_(usergroup.id==User.id)')
Base.prepare(engine, reflect=True)
session = Session(engine)
# Test this by querying the User table and then following the relationship
u = session.query(User).filter(User.oname == 'testuser').one()
print (u.oname)
for g in u1.weird:
print g.name
请参阅此处了解文档(包括其他示例):http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html?highlight=automap#specifying-classes-explicitly