简体   繁体   English

Wtforms-将FieldList数据写入mysql

[英]Wtforms- writing fieldlist data into mysql

Suppose I have a form like so: 假设我有一个像这样的表格:

Toys= FieldList(TextField('what toys do you have?'),min_entries=5)
Fruits= FieldList(TextField('what fruits do you have?'),min_entries=5)
Jewelry= FieldList(TextField('what jewelries do you have?'),min_entries=5)
Candy= FieldList(TextField('what candies do you have?'),min_entries=5)

without explicitly defining the submitted values like Toy1=form.Toys[1].data , how might I aggregate all the FieldList data in a form submission for writing into a SQL table like so:? 在没有显式定义诸如Toy1=form.Toys[1].data类的提交值的情况下,如何将所有FieldList数据汇总到表单提交中,以便写入SQL表,如下所示:

Toys | Fruits | Jewelry | Candy
ball  apple    Necklace  M&Ms
stick orange   Bracelet  skittles
top   grapes   tie clip  lollipop

For the sake of simplicity, I've set min_entries=5 for all fields. 为了简单起见,我为所有字段设置了min_entries=5 I tried using a for loop to append column names and values into a dictionary and writing it into my database like so: 我尝试使用for循环将列名和值添加到字典中,然后将其写入数据库,如下所示:

field_dict=dict()
    for f in form:
        if str(f.type) in ['FieldList']:
            for x in range(1,5):
                field_dict.update({f.name:f.data[x]})
                    sql_insert="INSERT INTO tablename ({}) values ({})".format(
                        ",".join(field_dict.keys()),
                        ",".join('"' + str(value) + '"' for value in field_dict.values()))
                    c.execute(sql_insert)

However, it's writing into the database everytime it encounters a Fieldlist , resulting in a table like: 但是,它每次遇到Fieldlist时都会将其写入数据库,从而产生如下表:

 Toys | Fruits | Jewelry | Candy
ball   NULL       NULL     NULL
ball   apple      NULL     NULL
ball   apple     Necklace  NULL
ball   apple     Necklace  M&Ms

My reading of the question is that you have a list of entries from your form you want to combine into a tuple and insert into the database.. 我对这个问题的理解是,您有一个表单中的条目列表,您希望将这些条目合并成一个元组并插入数据库中。

To save me some typing lets say you have: 为了节省我的时间,我假设您有:

# some list of keys obtained or hard coded as global..
KEYS = ['Toys', 'Fruits', 'Candy']

# and a form in which you have
Toys= FieldList(TextField('what toys do you have?'),min_entries=3)
Fruits= FieldList(TextField('what fruits do you have?'),min_entries=3)
Candy= FieldList(TextField('what candies do you have?'),min_entries=3)

Now your job is to cycle the form and package up a tuple: 现在您的工作是循环表单并打包一个元组:

form = Form()
for _i in range(3):
    tup = ()
    for key in KEYS:
        tup += (getattr(form, key)[_i].data,)
    sql = "INSERT INTO tablename ({}) values {}".format(
              ",".join(KEYS), str(tup))
    c.execute(sql)

Give it (or some debugged derivative!) a try 尝试一下(或一些调试的派生工具!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM