Search code examples
flaskflask-sqlalchemyflask-wtforms

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


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 ?


Solution

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