我可以检查sqlalchemy查询对象以查找已联接的表吗? [英] Can I inspect a sqlalchemy query object to find the already joined tables?

查看:76
本文介绍了我可以检查sqlalchemy查询对象以查找已联接的表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式构建搜索查询,为此,我正在联接一个表.

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.

说我的搜索功能如下:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆