问题描述
我正在使用Flask,SQLAlchemy和WTForms开发一个Web应用程序.我想通过数据库查询从 SelectField 中获得选择.
I'm developing a web app using Flask, SQLAlchemy and WTForms. I would like to get my choices in a SelectField from a query through my DB.
具有更多详细信息.
my_query = my_table.query.with_entities(My_Entities).all()
结果
我的班级
class MyForm(Form):
My_Var = SelectField(choices=RIGHT_HERE)
有什么办法吗?
推荐答案
在这种情况下,您可以使用WTForms中的扩展名.您要做的就是导入所需的QuerySelectField
:
In this situation what you can do is use the extensions that are in WTForms. What you do is import the QuerySelectField
that you need:
from wtforms.ext.sqlalchemy.fields import QuerySelectField
然后创建一个函数,该函数将查询数据库并返回所需的内容:
Then you create a function that will query the database and return the stuff you need:
def skill_level_choices():
return db.session.query(SkillLevel).all()
拥有查询对象后,可以使用query_factory
参数将其放入QuerySelectField
After you have the query object you can place it into your QuerySelectField
by using the query_factory
parameter
skill_level = QuerySelectField(u'Skill level',
validators=[Required()],
query_factory=skill_level_choices)
这篇关于从wtforms和flask-sqlalchemy中的数据库查询中获取选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!