简体   繁体   English

SQLAlchemy动态过滤器查询

[英]SQLAlchemy dynamic filter queries

I'm stuck on this database search problem: I have a PyQt5 widget with different checkBoxes. 我陷入了这个数据库搜索问题:我有一个带有不同复选框的PyQt5小部件。 Each of them represents a column from my database. 它们每个代表我数据库中的一列。 For example, 'worker_name' and 'department'. 例如,“ worker_name”和“ department”。 checkBoxes are placed near lineEdits, so user inserts some text into this lineEdit, than click on checkBox and 'Find' button. 复选框放置在lineEdits附近,因此用户可以在该lineEdit中插入一些文本,而不是单击checkBox和“查找”按钮。

Let's say, user insert 'John' in lineEdit, than press 'worker_name' checkBox and gets all docs of this worker via 假设用户在lineEdit中插入“ John”,而不是按“ worker_name”复选框,并通过获取该工作人员的所有文档

session.query(Doc).filter_by('worker_name'=text_from_lineEdit)

If user insert text in both lineEdits and pressed both checkBoxes ('worker_name' and 'department') query will look like this: 如果用户在两个lineEdits中都插入了文本并按下了两个复选框(“ worker_name”和“ department”),查询将如下所示:

session.query(Doc).filter_by('worker_name'=text_from_lineEdit, 'department'=text_from_lineEdit_2)

But what if I have many checkBoxes (as many as columns in DB table) and i don't know which of them will be pressed and which are not. 但是,如果我有许多复选框(与数据库表中的列一样多)并且我不知道将按下哪个复选框,该怎么办呢? How should I form the query in that case ? 在这种情况下,我应该如何形成查询? I mean I will have 'wrk_name','department' and 'date' and user could search only by 'worker_name' or by 'worker_name' + 'date' or with all of the checkBoxes. 我的意思是我将拥有“ wrk_name”,“部门”和“ date”,并且用户只能按“ worker_name”或“ worker_name” +“ date”或所有复选框进行搜索。

Is there any way to form database query dynamically relying on which arguments are given and which are not to include them in 'filter_by'/'filter or just ignore. 是否有任何方法可以动态地依赖于给定的参数以及不将其包含在'filter_by'/'filter中的参数来构成数据库查询,或者仅忽略它们。

Please, share your ideas about possible implementation of such functionality. 请分享您对此类功能的可能实现的想法。 Thx for your time. 谢谢你的时间。

Just remember that everything is an object in python, so you can dynamically build a list of filters and pass that to the filter() (or any other) method. 只需记住,所有内容都是python中的对象,因此您可以动态构建过滤器列表,并将其传递给filter()(或任何其他)方法。 Some pseudocode to illustrate the concept: 一些伪代码来说明这个概念:

flist = []
for inp in input:
    flist.append(Table.column == inp.property)

db.query(Table).filter(*flist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM