Last active
March 12, 2016 05:48
-
-
Save jungkoo/955712b71ae8a7bcaf49 to your computer and use it in GitHub Desktop.
[Flask-Admin] 'column_searchable_list' option support <ListField> type. (edit)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask_admin.contrib.mongoengine import ModelView | |
from flask_admin._compat import string_types | |
from mongoengine import ListField | |
class SupportListModelView(ModelView): | |
""" | |
'column_searchable_list' 옵션에 ListField 타입이 안되는걸 $in 쿼리로 지원하도록 함. | |
'column_searchable_list' option support <ListField> type | |
""" | |
def init_search(self): | |
if self.column_searchable_list: | |
for p in self.column_searchable_list: | |
if isinstance(p, string_types): | |
p = self.model._fields.get(p) # convert type | |
if p is None: | |
raise Exception('Invalid search field') | |
# [FIX] ListField<StringField | URLField | EmailField> | |
if isinstance(p, ListField): | |
p_sub = p.field | |
if type(p_sub) in self.allowed_search_types: | |
self._search_fields.append(p) | |
continue | |
field_type = type(p) | |
if (field_type not in self.allowed_search_types): | |
raise Exception('Can only search on text columns. ' + | |
'Failed to setup search for "%s"' % p) | |
self._search_fields.append(p) | |
return bool(self._search_fields) | |
def _search(self, query, search_term): | |
op, term = parse_like_term(search_term) | |
criteria = None | |
for field in self._search_fields: | |
# [FIX] ListField type ($in) | |
if isinstance(field, ListField): | |
flt = {'%s__%s' % (field.name, 'in'): (term,)} #=> { field_name : {$in: ["keyword"]} } | |
else: | |
flt = {'%s__%s' % (field.name, op): term} | |
q = mongoengine.Q(**flt) | |
if criteria is None: | |
criteria = q | |
else: | |
criteria |= q | |
return query.filter(criteria) |
Author
jungkoo
commented
Mar 12, 2016
- 예제
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment