flask-admin和pymongo搜索

时间:2014-08-08 09:46:46

标签: pymongo flask-admin

我有以下ModelView

from flask.ext.admin.contrib.pymongo import ModelView
from flask.ext import login
from wtforms import form

class ImageView(ModelView):

    column_labels = dict(
        recordId='Record Id',
        customerId='Customer Id',
        createdAt='Created At',
        updatedAt='Updated At',
        imagePath='Image Path',
        imageUrl='Image Url',
        imageType='Image Type',
        tag='Tag'
    )

    column_list = (
        '_id',
        'recordId',
        'customerId',
        'createdAt',
        'updatedAt',
        'imagePath',
        'imageUrl',
        'imageType',
        'tag'
    )

    column_sortable_list = (
        'customerId',
    )

    column_searchable_list = (
        'customerId',
    )

    form = ImageForm

    def is_accessible(self):
        return login.current_user.is_authenticated()

    def get_list(self, *args, **kwargs):
        count, data = super(ImageView, self).get_list(*args, **kwargs)
        return count, data

我希望我的客户ID可以搜索,但不幸的是因为它是mongodb中的整数类型,搜索将无法正常工作。如何实现自定义搜索功能来搜索整数?请注意,我的customerId完全有可能重复,因为我没有强制执行唯一性,这是我对此mongodb文档的意图。

1 个答案:

答案 0 :(得分:0)

解决了它。我所要做的就是使用custom_filters并应用我的自定义过滤器,它将传入的过滤器值转换为整数。

像这样:

class CustomFilterEqual(filters.BasePyMongoFilter):
    """
    Custom filter which casts the filter value as an integer, if possible.
    Failing which it will just set the value to an empty string, returning no results.
    """
    def apply(self, query, value):
        try:
            value = int(value)
        except:
            value = ""
        query.append({self.column: value})
        print(query)
        return query

    def operation(self):
        from flask.ext.admin.babel import gettext
        return gettext('equals')

在我上面的ImageView课程中,删除column_searchable_list属性并添加column_filters属性:

column_filters = (
    CustomFilterEqual('customerId', 'Customer Id'),
)