Improve default autocomplete query logic, w/ multiple ILIKE

e.g. to search for customer first and/or last name
This commit is contained in:
Lance Edgar 2021-09-24 17:17:19 -04:00
parent e6a92c5667
commit fbd12c7dfc

View file

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8; -*-
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2017 Lance Edgar
# Copyright © 2010-2021 Lance Edgar
#
# This file is part of Rattail.
#
@ -26,6 +26,8 @@ Autocomplete View
from __future__ import unicode_literals, absolute_import
import sqlalchemy as sa
from tailbone.views.core import View
from tailbone.db import Session
@ -45,11 +47,24 @@ class AutocompleteView(View):
return q
def make_query(self, term):
q = Session.query(self.mapped_class)
q = self.filter_query(q)
q = q.filter(getattr(self.mapped_class, self.fieldname).ilike('%%%s%%' % term))
q = q.order_by(getattr(self.mapped_class, self.fieldname))
return q
"""
Make and return the "complete" query for the given search term.
"""
# we are querying one table (and column) primarily
query = Session.query(self.mapped_class)
column = getattr(self.mapped_class, self.fieldname)
# filter according to business logic, if applicable
query = self.filter_query(query)
# filter according to search term(s)
criteria = [column.ilike('%{}%'.format(word))
for word in term.split()]
query = query.filter(sa.and_(*criteria))
# sort results by something meaningful
query = query.order_by(column)
return query
def query(self, term):
return self.make_query(term)