实现这一点的最简单方法是使用混合属性扩展:
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