首页 > 解决方案 > Flask-admin 可编辑的选择列基于行的过滤器

问题描述

我正在使用 flask-admin 对我的数据库模型进行简单的编辑。这是关于向客户出租滑雪板。

这是我的出租视图(相应的 sql_alchemy DB 模型):

class RentalView(ModelView):
    column_list = ("customer", "from_date", "to_date", "ski", "remarks")
    ...

客户和滑雪是各自模型的关系字段。我只想在编辑视图中显示在此时间段内未被其他人租用的这些滑雪板。

我一直在到处寻找如何动态设置编辑表单的选项,但它根本无法完全工作。

我试着做

def on_form_prefill(self, form, id):
    query = db.session.query... # do the query based on the rental "id"
    form.ski.query = query

这正确显示了过滤后的查询。但是,在提交表单时,.queryQuerySelectField 的属性又skiNone,因此导致 query = self.query or self.query_factory() TypeError: 'NoneType' object is not callable错误。不知道为什么要重置查询?!

有没有人知道如何根据已编辑对象的 id 处理动态查询的不同策略?

标签: flaskflask-sqlalchemyflask-admin

解决方案


使用此模式,覆盖视图的edit_form方法,实例化默认编辑表单(通过调用该super()方法,然后根据需要修改表单:

class RentalView(ModelView):

    # setup edit forms so that Ski relationship is filtered
    def edit_form(self, obj):

        # obj is the rental instance being edited
        _edit_form = super(RentalView, self).edit_form(obj)

        # setup your dynamic query here based on obj.id
        # for example

        _edit_form.ski.query_factory = lambda: Ski.query.filter(Ski.rental_id == obj.id).all()

        return _edit_form

推荐阅读