从 wtforms 和 flask-sqlalchemy 中的数据库查询中获取选择

Get choices from a DataBase query in wtforms and flask-sqlalchemy

我正在使用 Flask、SQLAlchemy 和 WTForms 开发网络应用程序。我想通过我的数据库查询在 SelectField 中获得我的选择。

更多详情。

my_query = my_table.query.with_entities(My_Entities).all()

结果

[(u'1',), (u'2',), (u'3',)]

我的class

class MyForm(Form):
    My_Var = SelectField(choices=RIGHT_HERE)

有什么办法吗?

在这种情况下,您可以使用 WTForms 中的扩展。您要做的是导入您需要的 QuerySelectField

from wtforms.ext.sqlalchemy.fields import QuerySelectField

然后你创建一个函数来查询数据库和return你需要的东西:

def skill_level_choices():      
    return db.session.query(SkillLevel).all()

获得查询对象后,您可以使用 query_factory 参数

将其放入 QuerySelectField
skill_level = QuerySelectField(u'Skill level',      
                               validators=[Required()],
                               query_factory=skill_level_choices)

使用数据库中的值填充 QuerySelectField

from wtforms.ext.sqlalchemy.fields import QuerySelectField

from flask_sqlalchemy import SQLAlchemy
name=QuerySelectField('Name',query_factory=lambda:my_table.query,get_label="username")

解法:

我在 wtformspeewee 上遇到了非常相似的问题,这是我的解决方法

class MyForm(FlaskForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.my_select_field.choices = [
            (el.id, el.description) for el in MyModel.select()
        ]

    my_select_field = SelectField("Field", coerce=int)

解释:

我们修改了原来的FlaskForm,使其在每次创建时都执行数据库查询。

因此 MyForm 数据选择保持最新。