我有以下命令,它按预期工作:
DBSession.query(Users).filter(or_(Users.first_name.contains(search_term),Users.last_name.contains(search_term))).all()
我在“我的用户”表格中搜索名字和姓氏,因此我可以通过搜索bob smith
或bob
找到smith
,但搜索{{1时}}。这显然是因为bob位于first_name列而不是bob smith
,因此它失败了。但是有没有办法在sqlalchemy中进行这种搜索?
我知道最糟糕的是我可以使用全名创建一个列,但我想我会问以防万一。我也将它标记为sql以防万一它可能与原始sql一起然后我将尝试根据原始查询来设置sqlalchemy版本。
答案 0 :(得分:0)
实现此目标的最简单方法是使用Hybrid Attributes扩展名:
from sqlalchemy.ext.hybrid import hybrid_property
class User(Base):
#...
first_name = Column(String, nullable=False)
last_name = Column(String, nullable=False)
@hybrid_property
def full_name(self):
return self.first_name + " " + self.last_name
@hybrid_property
def _full_name_last_first(self):
""" @note: used only for search [last, first]. """
return self.last_name + ", " + self.first_name
def test_search(search_term):
q = session.query(User)
q = q.filter(
or_(
User.first_name.contains(search_term),
User.last_name.contains(search_term),
User.full_name.contains(search_term),
User._full_name_last_first.contains(search_term),
),
)
q = q.order_by(User.id)
return q.all()
r1 = test_search('John Williams')
assert len(r1) == 1
r1 = test_search('Williams, Jo')
assert len(r1) == 1