我正在使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句