SQLAlchemy查询结果传入Jinja2模板后表单下拉列表为空问题
问题原因及解决方案
你的问题出在SQLAlchemy查询结果的处理上:db.execute()返回的是SQLAlchemy Result对象,并非直接可在Jinja2中遍历的列表,且每个结果是Row对象(不是纯字符串),导致模板无法正确渲染下拉选项。
修复步骤
1. 修改后端查询逻辑,转换为可直接使用的客户名称列表
在main.py中,将查询结果转换为字符串列表,推荐使用scalars().all()方法提取name字段的所有值:
@app.get("/user/signup") def signup(req: Request, db: Session = Depends(sess_db)): # 使用scalars()提取单个字段的值,再转成列表 list_of_customers = db.execute(text("SELECT name FROM resichain.customers ORDER BY name ASC")).scalars().all() return templates.TemplateResponse("signup.html", context={'request': req, 'list_of_customers': list_of_customers} )
如果需要保留Row对象(比如后续要用到多个字段),也可以用fetchall():
list_of_customers = db.execute(text("SELECT name FROM resichain.customers ORDER BY name ASC")).fetchall()
2. 模板对应调整(如果用Row对象的情况)
如果用fetchall(),模板里需要从Row对象中取出name值(或通过索引[0]):
<select name="customer" id="customer" class="form-control form-control-lg"> {% for customer in list_of_customers %} <option value="{{ customer.name }}">{{ customer.name }}</option> <!-- 或者用索引取值:{{ customer[0] }} --> {% endfor %} </select>
验证方法
修改后可以在后端打印list_of_customers的类型和内容,确认是字符串列表(或Row对象列表):
print(type(list_of_customers)) print(list_of_customers)
这样就能确保模板接收到可正确遍历的数据,下拉框会正常填充客户名称。
内容的提问来源于stack exchange,提问作者user1931485
相关产品推荐
相关产品推荐

