当变量数未知时插入Sqlalchemy

2024-04-19 16:16:31 发布

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

我有一个动态允许用户创建表的html文档。有一个“添加行”按钮,通过单击该按钮,他们可以向表中添加一行输入。添加的代码如下所示:

<tr>
    <td class = 'sct_components_input'> <input class = 'sct_components_input_5'> </input> </td>
    <td class = 'sct_components_input'> <input class = 'sct_components_input_5'> </input> </td>
    <td class = 'sct_components_input'> <input class = 'sct_components_input_10'> </input> </td>
    <td class = 'sct_components_input'> <input class = 'sct_components_input_10'> </input> </td>
    <td class = 'sct_components_input'> <textarea class = 'sct_components_input_15'> </textarea> </td>
    <td class = 'sct_components_input'> <input class = 'sct_components_input_5'> </input> </td>
    <td class = 'sct_components_input'> <input class = 'sct_components_input_5'> </input> </td>
    <td class = 'sct_components_input'> <textarea class = 'sct_components_input_15'> </textarea> </td>
</tr>

所以我只剩下一个表,其中有很多输入,用户创建了X行,这个值会随着每个用户而改变。我需要使用FLASK(sqlalchemy)将所有这些输入上传到mysql表。但我不知道如何上传这些输入。你知道吗

我最好的猜测是,您必须多次循环sqlalchemy upload查询,一次上载一行。类似于将CSV文件上传到sqlalchemy。你知道吗

但是,我不知道如何给每个输入一个唯一的'名称',从而允许表单上传。你知道吗


Tags: 代码用户文档flaskinputsqlalchemyhtmlcomponents
1条回答
网友
1楼 · 发布于 2024-04-19 16:16:31

假设动态生成的表如下所示:

<form>
  <table>
    <tr>
      <td><input name="first_name"></td>
      <td><input name="age"></td>
    </tr>
    <tr>
      <td><input name="first_name"></td>
      <td><input name="age"></td>
    </tr>
  </table>
</form>

然后,在python中,您可以按如下方式访问所有数据:

first_names = request.form.getlist('first_name')
ages = request.form.getlist('age')
for first_name, age in zip(first_names, ages):
    person = Person(first_name, age)
    db.session.add(person)
db.session.commit()

此方法允许您以相同的名称获取DOM中的所有输入元素。然后使用zip()将获取的姓名列表与获取的年龄列表组合起来。通过这种方式,您可以动态地向数据库添加一些匹配的数据。你知道吗

另一种方法是为DOM元素指定唯一的名称,但这要简单一些。你知道吗

相关问题 更多 >