用SQL查询填充WTForms SelectField



我想用此查询返回的行填充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'])

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

在我使用的一个项目中,如下所示:

型号

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

希望这会有所帮助。

解决方案可能看起来像下面的代码。

假设您有两个文件: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)

解决方案:

我遇到了相当简单的问题,这是我的解决方法

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字段数据选择总是保持最新。

我通过执行以下操作来解决此问题:

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')]

最新更新