我可以检查 sqlalchemy 查询对象以查找已连接的表吗? [英] Can I inspect a sqlalchemy query object to find the already joined tables?
问题描述
我正在尝试以编程方式构建搜索查询,为此,我加入了一个表.
I'm trying to programmatically build a search query, and to do so, I'm joining a table.
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
class Tag(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
title = db.Column(db.String(128))
description = db.Column(db.String(128))
这是一个人为的例子 - 我希望它是有道理的.
This is a bit of a contrived example - I hope it makes sense.
假设我的搜索功能类似于:
Say my search function looks something like:
def search(title_arg, desc_arg):
query = User.query
if title_arg:
query = query.join(Tag)
query = query.filter(Tag.title.contains(title_arg))
if desc_arg:
query = query.join(Tag)
query = query.filter(Tag.description.contains(desc_arg))
return query
以前,我一直跟踪哪些表已加入列表,如果该表在列表中,则假定它已加入,只需添加过滤器即可.
Previously, I’ve kept track of what tables that have already been joined in a list, and if the table is in the list, assume it’s already joined, and just add the filter.
如果我可以查看查询对象,看到 Tag
已经加入,并且如果是,则跳过它会很酷.我有一些更复杂的查询构建,可以真正从中受益.
It would be cool if I could look at the query object, see that Tag
is already joined, and skip it if so. I have some more complex query building that would really benefit from this.
如果我遗漏了一种完全不同的搜索查询构建策略,那也太好了.或者,如果上面的代码在我两次加入表格时没问题,那也是很好的信息.非常感谢任何帮助!!!
If there’s a completely different strategy for query building for searches that I’ve missed, that would be great too. Or, if the above code is fine if I join the table twice, that's great info as well. Any help is incredibly appreciated!!!
推荐答案
您可以在 query._join_entities
joined_tables = [mapper.class_ for mapper in query._join_entities]
这篇关于我可以检查 sqlalchemy 查询对象以查找已连接的表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!