【发布时间】:2016-09-06 10:29:19
【问题描述】:
我正在用烧瓶和 Flask-SQLAlchemy 编写一个简单的 BBS 系统。我想实现一个简单的搜索功能,它找出给定列表中所有键出现在两个字段中的任何一个字段中的所有记录:“标题”和“内容”。这是我现在的做法:
# Topic is just a table and has some fields, such as title and content.
keys = keywords.split(' ')
all_topics = set(Topic.query.filter(
and_(*[Topic.title.like("%" + k + "%") for k in keys])).all())
content_topics = set(Topic.query.filter(
and_(*[Topic.content.like("%" + k + "%") for k in keys])).all())
# Remove duplicated search result, because the keywords may
# occur in both title and content.
all_topics.update(content_topics)
但这不是很合适。因为对于一个指定的键,它可以出现在标题或内容中。
更新:
为了更清楚,我想举一个简单的例子。 db 中的记录如下:
Id | Title | Content
---| --- | ---
| 1 | This is a demo | For test
| 2 | This is also a demo | Again
| 3 | This demo test | HaHa
当我搜索“This test”时,我当前的函数只返回record 3。但我也希望record 1 也能被退回。我应该怎么办?
【问题讨论】:
标签: python-2.7 flask-sqlalchemy