使用SQL查询填充WTForms SelectField

时间:2017-04-21 17:16:55

标签: python mysql sqlite flask wtforms

我想用这个查询返回的行填充WTForms SelectField:

cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")

查询返回滑雪长度为不同类型滑雪板的行。 cur.fetchall()返回以下元组:

[(70,), (75,), (82,), (88,), (105,), (115,), (125,), (132,), (140,), (150,), (160,), (170,)]

我如何将这些数字添加到SelectField,以便每个滑雪长度都是它自己的可选择的选择?如果我手动完成此操作,我会做以下事情:

ski_size = SelectField('Ski size', choices=['70', '70', '75', '75'])

......等等所有不同的长度。

4 个答案:

答案 0 :(得分:3)

在我使用的其中一个项目中如下:

模型

class PropertyType(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    title = db.Column(db.String(255), nullable=False)

    def __repr__(self):
        return str(self.id)

并以表格

from wtforms.ext.sqlalchemy.fields import QuerySelectField

class PropertyEditor(Form):
    property_type = QuerySelectField(
        'Property Type',
        query_factory=lambda: models.PropertyType.query,
        allow_blank=False
    )
    //Other remaining fields

希望这有帮助。

答案 1 :(得分:0)

我设法通过以下方式解决了这个问题:

def fetch_available_items(table_name, column):
    with sqlite3.connect('database.db') as con:
        cur = con.cursor()
        cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
        return cur.fetchall()

class SkipakkeForm(Form):
    alpin_ski = SelectField('Select your ski size', choices=[])

@app.route('/skipakke')
def skipakke():
    form = SkipakkeForm

    # Clear the SelectField on page load
    form.alpin_ski.choices = []        

    for row in fetch_available_items('skipakke_alpin_ski', 'length'):
        stock = str(row[0])
        form.alpin_ski.choices += [(stock, stock + ' cm')]

答案 2 :(得分:0)

解决方案可能类似于下面的代码。

我们假设您有两个文件:routes.pyviews.py

routes.py文件中你放了这个

from flask_wtf import FlaskForm
from wtforms import SelectField

# Here we have class to render ski
class SkiForm(FlaskForm):
    ski = SelectField('Ski size')

views.py文件中你放了这个

# Import your SkiForm class from `routes.py` file
from routes import SkiForm

# Here you define `cur`
cur = ...

# Now let's define a method to return rendered page with SkiForm
def show_ski_to_user():
    # List of skies
    cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
    skies = cur.fetchall()

    # create form instance
    form = SkiForm()
    # Now add ski length to the options of select field
    # it must be list with options with (key, value) data
    form.ski.choices = [(ski, ski) for ski in skies]
    # If you want to use id or other data as `key` you can change it in list generator
    if form.validate():
        # your code goes here

    return render_template('any_file.html', form=form)

请记住,默认情况下key值为unicode。如果要使用int或其他数据类型,请在SkiForm类中使用coerce参数,如此

class SkiForm(FlaskForm):
    ski = SelectField('Ski size', coerce=int)

答案 3 :(得分:0)

解决方案:

我遇到了类似的问题,这是我的解决方法

class SkiForm(FlaskForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        cur.execute("SELECT length FROM skipakke_alpin_ski WHERE stock > 0")
        skies = cur.fetchall()

        self.ski_size.choices = [
            (ski , ski) for ski in skies
        ]

    ski_size = SelectField("Ski size")

说明:

我们修改了原始FlaskForm,以便在每次创建数据库时都执行数据库查询。

因此SkiForm字段数据选择始终保持最新。