Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[Flask-Admin] 'column_searchable_list' option support <ListField> type. (edit)
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:
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)
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' % (, 'in'): (term,)} #=> { field_name : {$in: ["keyword"]} }
flt = {'%s__%s' % (, op): term}
q = mongoengine.Q(**flt)
if criteria is None:
criteria = q
criteria |= q
return query.filter(criteria)

This comment has been minimized.

Copy link
Owner Author

jungkoo commented Mar 12, 2016

  • 예제
class Post(Document):
    id = StringField(required=True, primary_key=True)
    title = StringField()
    body = StringField()
    tags = ListField(StringField())

class PostView(SupportListModelView):
    column_searchable_list = ('tags', )

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'db': 'blog'}
db = MongoEngine()
admin = Admin(app, name='blog', template_mode='bootstrap3')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.