flask - 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
这正确显示了过滤后的查询。但是,在提交表单时,.query
QuerySelectField 的属性又ski
是None
,因此导致 query = self.query or self.query_factory() TypeError: 'NoneType' object is not callable
错误。不知道为什么要重置查询?!
有没有人知道如何根据已编辑对象的 id 处理动态查询的不同策略?
解决方案
使用此模式,覆盖视图的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
推荐阅读
- vhdl - 从 vhdl 中的另一个常量初始化记录的常量数组
- python - 到上一年和下一年的天数 - Pandas
- javascript - 从字符串JS中提取数据
- python - 尝试在朋友的 PC 上安装 PyCharm,但此对话框不断弹出,并且无法检测到解释器
- php - Payu(肯尼亚)使用 php 中的肥皂进行支付集成
- javascript - 在浏览器中保持 Flask 在没有网页的情况下运行
- c# - 将泛型类转换为不同的类型
- html - 为什么 Animated.css 不能按照网站上的说明工作?
- azure-sql-database - 是否有适用于 Azure 数据工厂、azure sql db 和 Synapse DB 的模拟器
- c# - 如何强制 Uri 使用 baseUri?