SQLAlchemy-“动态过滤器” [英] SQLAlchemy - "Dynamic Filter"

查看:128
本文介绍了SQLAlchemy-“动态过滤器”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用SQLAlchemy。我决定使用它,因为在sqlite查询中间使用了很多字符串表达式。

I have just started using SQLAlchemy. I decided to use it because I was using a lot of string expression in the middle of my sqlite queries.

所以,这就是我的问题。我的桌子上有很多设备,每个设备都有维护级别的日期。关键是用户可以选择他想在屏幕上看到的维护级别。因此,我应该针对他选择的每种维护级别组合调整我的SQLAlchemmy。

So, that is my problem. I have a table with many equipment and each of them has dates for level of maintanance. The point is that the user can select the maintance level he wants to see on the screen. So, I should "adjust" my SQLAlchemmy for each combination of maintanance level he's chosen.

例如,在原始SQLite中。

For exemple, in the raw SQLite.

选择*在哪里(设备IN [])并且m_level1 =日期和m_level2 =日期....)

SELECT * WHERE (equipment IN []) AND m_level1 = DATE AND m_level2 = DATE ....)

因此,对于每个if条件,可能有很多组合,这取决于选中了哪些复选框。如前所述,在原始SQL中,我使用了很多字符串来达到我的目标。但是我想使用SQLAlchemy改进代码。

So, it is possible to have many combination for each if condition, it depends which checkboxes are checked. As I mentioned, in the raw SQL I used a lot of string to reach my goal. But I want to improve the code using SQLAlchemy.

对不起,我现在没有代码!谢谢你们 !

Sorry I do not have the code now ! Thank you all !

推荐答案

我假设您正在使用ORM。

I assume you are using the ORM.

情况下, filter 函数返回一个查询对象。您可以通过以下方式有条件地构建查询

in that case, the filter function returns a query object. You can conditionaly build the query by doing something like

query = Session.query(schema.Object).filter_by(attribute=value)
if condition:
    query = query.filter_by(condition_attr=condition_val)
if another_condition:
    query = query.filter_by(another=another_val)

#then finally execute it

results = query.all()

这篇关于SQLAlchemy-“动态过滤器”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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