You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django从数据表获取行数据后前端显示为None问题求助

问题排查与修复方案

你的问题核心出在数据库查询的代码逻辑错误,导致最终传递给模板的rows始终是初始的None,下面一步步拆解问题和修复方法:

1. 核心错误:错误使用cursor.execute()的返回值

在Python的数据库API规范里,cursor.execute()执行SELECT语句时,返回的是None(而非游标对象)——它只负责执行SQL语句,查询结果需要通过原游标对象调用fetchall()来获取。

你原来的代码里:

a = cursor.execute(locname)
rows = a.fetchall()

这里a其实是None,调用a.fetchall()会直接抛出AttributeError,但由于没有异常捕获,代码可能提前终止,导致rows还是初始赋值的None,最终传到模板里就显示成了None。

修正后的views.py代码

rows = None
locname = "select location_name from locations"
cursor = con.cursor()
# 直接执行SQL,不需要接收execute的返回值
cursor.execute(locname)
# 通过原cursor对象获取查询结果
rows = cursor.fetchall()
# 用完游标记得关闭
cursor.close()
return render(request, 'project/output.html', {'rows': rows})

2. 额外优化建议

(1)添加异常捕获,避免程序崩溃

数据库操作可能出现连接失败、SQL语法错误等问题,建议加异常处理,确保代码健壮性:

rows = []
locname = "select location_name from locations"
try:
    cursor = con.cursor()
    cursor.execute(locname)
    rows = cursor.fetchall()
except Exception as e:
    print(f"查询出错: {str(e)}")  # 控制台查看错误详情
finally:
    if 'cursor' in locals():
        cursor.close()
return render(request, 'project/output.html', {'rows': rows})

(2)模板优化:更友好的展示数据

直接显示{{ rows }}会输出类似[('北京',), ('上海',)]的原始元组列表,建议遍历显示单个值,同时处理空数据的情况:

<html>
<body>
    <h3>位置列表</h3>
    {% for row in rows %}
        <p>{{ row.0 }}</p>  <!-- row是元组,取第一个元素就是location_name -->
    {% empty %}
        <p>暂无位置数据</p>
    {% endfor %}
</body>
</html>

(3)验证数据库数据

最后确认一下locations表中是否真的有数据,如果表是空的,fetchall()会返回空列表,模板会显示暂无位置数据,而不是None。

内容的提问来源于stack exchange,提问作者Divya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:43:51