【问题标题】:Populate a WTForms SelectField with an SQL query使用 SQL 查询填充 WTForms SelectField
【发布时间】:2017-09-18 19:14:29
【问题描述】:

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

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

【问题讨论】:

    标签: python mysql sqlite flask wtforms


    【解决方案1】:

    在我使用过的项目之一中:

    型号

    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
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 优秀的答案。它帮助我解决了我在验证表单时发现的问题。恭喜你对这个概念有很好的理解。 'UNICODE' 的评论是关键 非常感谢!!!
      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        解决方案:

        我遇到了非常相似的问题,这是我的解决方法

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-30
          • 1970-01-01
          • 2019-03-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-04
          • 1970-01-01
          相关资源
          最近更新 更多