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

独自空忆成欢 提交于 2020-07-18 08:02:11

问题


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.

With more details.

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

Result

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

My class

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

Is there any way ?


回答1:


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()

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)



回答2:


Populate QuerySelectField with values from Databaase

from wtforms.ext.sqlalchemy.fields import QuerySelectField

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



回答3:


Solution:

I had quite simmilar problem with wtforms and peewee, and here is my workaround

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)

Explanation:

We modified original FlaskForm, so that it executs database query each time when it is being created.

So MyForm data choices stays up to date.



来源:https://stackoverflow.com/questions/35314102/get-choices-from-a-database-query-in-wtforms-and-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!