web.py - 如何将 db.query(sql) 的结果转换为字典列表?
我对 Python 和 web.py(我目前正在使用)都很陌生,所以请耐心等待。
在官方文档中:
import web
db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='')
results = db.query("SELECT COUNT(*) AS total_users FROM users")
print results[0].total_users # -> prints number of entries in 'users' table
看起来查询的结果是一个字典列表 {total_user: num} 对?
我的情况非常相似:对数据库运行 SELECT,希望获得 key:value 数据的列表。
在 models.py 中:
def get_items:
return self.db.query("SELECT title FROM news")
在 code.py 中:
items = model.get_items
return render.list(items)
在 templates/list.html 中:
$def with (items)
$for item in items:
<p>$item.title</p>
但是,代码会触发错误,因为“'tuple'对象没有属性'title'”。 我做错了什么?预先感谢您的帮助。
I'm new to both Python and web.py (which I am currently using) so please bear with me.
import web
db = web.database(dbn='postgres', db='mydata', user='dbuser', pw='')
results = db.query("SELECT COUNT(*) AS total_users FROM users")
print results[0].total_users # -> prints number of entries in 'users' table
Looks like the result of the query is a list of dictionaries {total_user: num} right?
My situation is very similar: running a SELECT against the database, hoping to get a list of key:value data.
In models.py:
def get_items:
return self.db.query("SELECT title FROM news")
In code.py:
items = model.get_items
return render.list(items)
In templates/list.html:
$def with (items)
$for item in items:
<p>$item.title</p>
However, the code triggers an error as "'tuple' object has no attribute 'title'".
What have I done wrong? Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它会触发,因为您只是从新闻中选择标题属性,这显然会给出像 (a,b,c,d) 这样的元组作为结果。
如果你想要一个对象作为结果,请执行以下操作
It will trigger, because you are just selecting only the title attribute from news, which obvioulsy will give tuple like (a,b,c,d) as result.
if you want a object as result,do something like this