Skip to content

Instantly share code, notes, and snippets.

@kootenpv
Last active March 31, 2018 19:59
Show Gist options
  • Save kootenpv/038d58d70fc338ef742c613a39408069 to your computer and use it in GitHub Desktop.
Save kootenpv/038d58d70fc338ef742c613a39408069 to your computer and use it in GitHub Desktop.
MyModelView including a search limited to a field using syntax like `username:kootenpv`
# Authors: Leonid R. and Pascal van Kooten
from flask_admin.contrib.sqla import ModelView
from flask_admin.contrib.sqla import tools
from sqlalchemy import or_
from sqlalchemy.sql.expression import cast
from sqlalchemy import Unicode
class MyModelView(ModelView):
# modifies existing _apply_search
# https://github.com/flask-admin/flask-admin/blob/master/flask_admin/contrib/sqla/view.py#L874
def _apply_search(self, query, count_query, joins, count_joins, search):
"""
Apply search to a query.
"""
terms = search.split(' ')
for term in terms:
if not term:
continue
#### this is the extra part ####
if ":" in term:
field_limit, term = term.split(":")
else:
field_limit, term = None, term
################################
stmt = tools.parse_like_term(term)
filter_stmt = []
count_filter_stmt = []
for field, path in self._search_fields:
if field_limit and field_limit != field.name:
continue
query, joins, alias = self._apply_path_joins(
query, joins, path, inner_join=False)
count_alias = None
if count_query is not None:
count_query, count_joins, count_alias = self._apply_path_joins(count_query,
count_joins,
path,
inner_join=False)
column = field if alias is None else getattr(alias, field.key)
filter_stmt.append(cast(column, Unicode).ilike(stmt))
if count_filter_stmt is not None:
column = field if count_alias is None else getattr(count_alias, field.key)
count_filter_stmt.append(cast(column, Unicode).ilike(stmt))
query = query.filter(or_(*filter_stmt))
if count_query is not None:
count_query = count_query.filter(or_(*count_filter_stmt))
return query, count_query, joins, count_joins
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment