刚开始学习 python django 框架,我想在 html 页面中显示自定义查询结果。
def index(request):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM polls_post")
context ={
'all_posts':cursor.fetchall()
}
在我的 html 页面中
<ul>
{% for post in all_posts %}
<li>{{ post }}</li>
{% endfor %}
</ul>
但是它将值显示为元组,所以我怎样才能得到带有表列名的查询结果,比如我可以这样打印值
<ul>
{% for post in all_posts %}
<li>{{ post.title }}</li>
<li>{{ post.name }}</li>
{% endfor %}
</ul>
请您参考如下方法:
你不能 - 使用游标你需要在 View 中自己重新打包数据,然后将对象列表传递给模板。
有点像
posts = []
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM polls_post")
for obj in cursor.fetchall():
posts.append({"title": obj[0], "name": obj[1]})
context = {'all_posts':cursor.fetchall()}
不过我想您更愿意使用 Django 的 ORM 框架。看看 Model reference那么。
