2016-11-16 85 views
0

在Flask Admin中,我得到了一串字符串值(我无法更改数据库定义)。在索引视图中过滤此列时,用户应该能够从下拉列表中选择值。如何计算Flask Admin中列过滤器的下拉选项?

当用户选择过滤器时,应计算过滤器的可能选项。所以我需要一种方法来设置基于自定义模型查询的选项。当列被索引时,查询速度非常快。

SQLA custom filter example仅显示如何应用自定义过滤器,但不显示如何使过滤器的选项变为动态。

回答

1

选项参数可以是调用所以这样做以下(使用你链接到为例):

def get_all_last_names(): 
    unique_last_names = User.query.with_entities(User.last_name.distinct().label("last_name")).order_by(User.last_name.asc()).all() 
    return [(user.last_name, user.last_name) for user in unique_last_names] 

class UserAdmin(sqla.ModelView): 

    column_filters = [ 
     FilterEqual(column=User.last_name, name='Last Name', options=get_all_last_names), 
    ] 

    # This is probably NOT the correct way to refresh the filters cache 
    @expose('/') 
    def index_view(self): 
     self._refresh_filters_cache() 
     return super(UserAdmin, self).index_view() 
+0

Mmmh,当应用程序启动此功能被调用。即使页面重新载入也不会触发它重新加载:-( – Sebi

+0

@Sebi - 您需要更新过滤器缓存 - 我已更新我的答案 – pjcunningham