sqlalchemy:如何通过一个查询连接多个表?
我有以下SQLAlchemy映射的类:
class User(Base): __tablename__ = 'users' email = Column(String, primary_key=True) name = Column(String) class Document(Base): __tablename__ = "documents" name = Column(String, primary_key=True) author = Column(String, ForeignKey("users.email")) class DocumentsPermissions(Base): __tablename__ = "documents_permissions" readAllowed = Column(Boolean) writeAllowed = Column(Boolean) document = Column(String, ForeignKey("documents.name"))
我需要得到这样的表user.email = "user@email.com"
:
email | name | document_name | document_readAllowed | document_writeAllowed
如何使用SQLAlchemy的一个查询请求? 下面的代码不适用于我:
result = session.query(User, Document, DocumentPermission).filter_by(email = "user@email.com").all()
谢谢,
尝试这个
q = Session.query(User,Document,DocumentPermissions).filter(User.email == Document.author).\ filter(Document.name == DocumentPermissions.document).\ filter(User.email == 'someemail').all()
一个好的风格是设置一些关系和权限的主键(实际上,通常是设置整数主键的好方法,但是不pipe):
class User(Base): __tablename__ = 'users' email = Column(String, primary_key=True) name = Column(String) class Document(Base): __tablename__ = "documents" name = Column(String, primary_key=True) author_email = Column(String, ForeignKey("users.email")) author = relation(User, backref='documents') class DocumentsPermissions(Base): __tablename__ = "documents_permissions" id = Column(Integer, primary_key=True) readAllowed = Column(Boolean) writeAllowed = Column(Boolean) document_name = Column(String, ForeignKey("documents.name")) document = relation(Document, backref = 'permissions')
然后用连接做一个简单的查询:
query = session.query(User, Document, DocumentsPermissions).join(Document).join(DocumentsPermissions)
这个函数将产生所需的表作为元组列表。
def get_documents_by_user_email(email): query = session.query(User.email, User.name, Document.name, DocumentsPermissions.readAllowed, DocumentsPermissions.writeAllowed,) join_query = query.join(Document).join(DocumentsPermissions) return join_query.filter(User.email == email).all() user_docs = get_documents_by_user_email(email)
扩展阿卜杜勒的答案,您可以通过join列获得一个KeyedTuple
而不是离散的行集合:
q = Session.query(*User.__table__.columns + Document.__table__.columns).\ select_from(User).\ join(Document, User.email == Document.author).\ filter(User.email == 'someemail').all()