Skip to content

Instantly share code, notes, and snippets.

Embed
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:
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)
@jungkoo

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()
db.init_app(app)
admin = Admin(app, name='blog', template_mode='bootstrap3')
admin.add_view(PostView(Post))
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.