[英]How to create a dynamic SQL query
I have a large sqlite table of 33k records (movies) . 我有一个33k记录(电影)的大型sqlite表。 I want to give the user the ability to search in that table via filters .
我想让用户能够通过过滤器在该表中进行搜索。 Each movie record has 10 fields : Actors, Directors, Runtime, Genre, Rating and few more .
每部电影记录都有10个字段:演员,导演,放映时间,类型,评分等。 The only filters available for the user to use are people (Include Actors and Directors), Genre, Rating and Runtime .
供用户使用的唯一过滤器是人员(包括演员和导演),类型,等级和运行时间。
The problem is that the user can use two filters or more, hence we don't really know which filter will be used . 问题在于用户可以使用两个或更多个过滤器,因此我们实际上并不知道将使用哪个过滤器。 Filters values are passed via an HTTP req to the server which process it and create an SQL query based on filters to execute on the db .
过滤器值通过HTTP请求传递给服务器,服务器对该请求进行处理,并根据要在db上执行的过滤器创建SQL查询。
What I can't understand is how can I create an SQL query if I don't know which filters will be used ? 我不明白的是,如果我不知道将使用哪些过滤器,该如何创建SQL查询? Because only used filters will be sent to the server .
因为只会将使用过的过滤器发送到服务器。
Basically I want to find a way to create an SQL query based on sent filters by each users . 基本上,我想找到一种基于每个用户发送的筛选器创建SQL查询的方法。
If you're given a list of filters, you can just apply Query.filter_by()
or Query.filter()
over and over: 如果获得过滤器列表,则可以
Query.filter_by()
应用Query.filter_by()
或Query.filter()
:
filters = [
('rating', 3),
('runtime', 90),
('genre', 'documentary')
]
query = session.query(Movie)
for column, value in filters:
# Make sure `column` and `value` are legal values!
query = query.filter_by(**{column: value})
Since the query is evaluated only at the end, you're essentially doing: 由于查询仅在最后进行评估,因此您实际上是在做:
query = query.filter_by(...).filter_by(...) ...
In the last line, filter_by(**{column: value})
is notation for filter_by(value_of_column_variable=value)
. 在最后一行,
filter_by(**{column: value})
是filter_by(value_of_column_variable=value)
表示法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.