我正在尝试组装一个适用于数据库的烧瓶应用程序,作为课程的最终项目。我已经到了最后,遇到了一个令我困惑的错误。我对 Python 还很陌生,所以我希望这里缺少一些非常基本的东西......
因为它是 Flask,所以有一堆
html
文件,所以很难在这里重现 MWE。但这是基本问题:
在此功能中
@app.route('/view_meal', methods=['GET', 'POST'])
def view_meal():
if request.method == 'POST':
selected_meal_id = request.form['selected_meal']
#get all the food_items associated with this meal
rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'")
food1 = display_table('food_item', where_condition=f"id = '{rows[4]}'")
food2 = display_table('food_item', where_condition=f"id = '{rows[5]}'")
food3 = display_table('food_item', where_condition=f"id = '{rows[6]}'")
food4 = display_table('food_item', where_condition=f"id = '{rows[7]}'")
food5 = display_table('food_item', where_condition=f"id = '{rows[8]}'")
foods = [food1, food2, food3, food4, food5]
return render_template('display_meal.html', rows = rows, foods=foods)
else:
rows = display_table('meal')
return render_template('view_meal.html', items=rows)
在我的第一次迭代中,我只是获取与不同食物相关的 id_numbers,效果很好。所以我知道我正确地从表格中获取了
selected_meal_id
,并且该行
rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'")
正确查询数据库。
display_table
函数只是一个传入表名和SELECT * FROM
子句的WHERE
。
作为进一步的测试,在一个单独的小 Python 文件中,我在该数据库中查询了我正在使用的 meal_id
result = cur.execute("SELECT * FROM meal WHERE id='PCKCMH0S'").fetchall()
print(result)
这就是结果
[('PCKCMH0S', '英式早餐', '胖子', '3/9/2024', 'BQD3MPHM', ‘77WWB0BQ’、‘QGH6DV8S’、‘I4VD1IE7’、‘QGH6DV8S’)]
这就是
rows
中应该包含的内容
但是线
food1 = display_table('food_item', where_condition=f"id = '{rows[4]}'")
正在抛出一个
list index out of range
,并在 rows[4]
下划线。我在这里缺少什么? rows
中应该有九个元素
rows = [('PCKCMH0S', 'English Breakfast', 'Fatty', '3/9/2024', 'BQD3MPHM', '77WWB0BQ', 'QGH6DV8S', 'I4VD1IE7', 'QGH6DV8S')]
这是一个包含单个元组的列表。然后
rows[4]
尝试从该外部列表中获取第五个元素,但由于它只包含一个元素,这将出错。
解决方法是获取元组,然后索引该元组。比如:
rows = display_table('meal', where_condition=f"id = '{selected_meal_id}'")
row = rows[0]
food1 = display_table('food_item', where_condition=f"id = '{row[4]}'")
food2 = display_table('food_item', where_condition=f"id = '{row[5]}'")