使用SQL查询填充WTForms SelectField

2024-10-01 17:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

我该怎么把这些数字加到一个SelectField上,这样每一个滑雪板的长度都是它自己选择的呢?如果我是手动完成的,我会执行以下操作:

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

。。。等等,所有不同的长度。在


Tags: from类型executesizestockwhereselectlength
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)

在形式上

^{pr2}$

希望这有帮助。在

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

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

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

假设有两个文件:routes.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文件中,您将此

^{pr2}$

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

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

相关问题 更多 >

    热门问题