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 = "[email protected]"
:
email | name | document_name | document_readAllowed | document_writeAllowed
如何使用 SQLAlchemy 的一个查询请求来实现它?下面的代码对我不起作用:
result = session.query(User, Document, DocumentPermission).filter_by(email = "[email protected]").all()
谢谢,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个
Try this
正如 @letitbee 所说,最佳实践是将主键分配给表并正确定义关系以允许正确的 ORM 查询。话虽这么说...
如果您有兴趣编写如下查询:
那么您应该执行以下操作:
如果相反,您想做类似的操作:
那么您应该执行以下操作:
一个注释关于这一点...
有关更多信息,请访问 文档< /a>.
As @letitbee said, its best practice to assign primary keys to tables and properly define the relationships to allow for proper ORM querying. That being said...
If you're interested in writing a query along the lines of:
Then you should go for something like:
If instead, you want to do something like:
Then you should do something along the lines of:
One note about that...
For more information, visit the docs.
一个好的风格是设置一些关系和权限的主键(实际上,通常为所有内容设置整数主键是一个很好的风格,但无论如何):
然后使用连接进行简单的查询:
A good style would be to setup some relations and a primary key for permissions (actually, usually it is good style to setup integer primary keys for everything, but whatever):
Then do a simple query with joins:
扩展阿卜杜勒的答案,您可以获得
KeyedTuple
通过连接列来代替离散的行集合:Expanding on Abdul's answer, you can obtain a
KeyedTuple
instead of a discrete collection of rows by joining the columns:该函数将生成所需的表作为元组列表。
This function will produce required table as list of tuples.
sqlalchemy中的联接查询
我们可以使用SQLAlchemy实现联接(从多个表中提取数据)。
下面的链接提到了详细信息:
https://evidenttutorials.com/SQL/join- sqlalchemy 中的查询/
Join query in sqlalchemy
We can achieve the joins (extracting data from multiple tables) using SQLAlchemy.
Details are mentioned in below link:
https://evidenttutorials.com/SQL/join-query-in-sqlalchemy/