我正在使用 Python 的 Peewee ORM 来处理 MySQL 数据库。Peewee 提供了一个名为“fn”的对象,它允许您对数据库进行某些类型的调用。我想拨打的电话之一如下:
Blocks.select(Blocks, fn.Count(Blocks.height))
Run Code Online (Sandbox Code Playgroud)
其中 Blocks 是我的数据库中的一个表,其中有一列名为 height。该语法直接取自 Peewee 的文档,即
User.select(
User, fn.Count(Tweet.id))
Run Code Online (Sandbox Code Playgroud)
位于此处http://peewee.readthedocs.org/en/latest/peewee/querying.html。请注意,我的 python 文件顶部还有以下几行
import peewee
from peewee import *
from peewee import fn
Run Code Online (Sandbox Code Playgroud)
然而,当我运行这段代码时,它不起作用,并且它吐出这个
<class '__main__.Blocks'> SELECT t1.`height`, t1.`hash`, t1.`time`, t1.`confirmations`, t1.`size`, t1.`version`, t1.`merkleRoot`, t1.`numTX`, t1.`nonce`, t1.`bits`, t1.`difficulty`, t1.`chainwork`, t1.`previousBlockHash`, t1.`nextBlockHash`, Count(t1.`height`) FROM `blocks` AS t1 []
Run Code Online (Sandbox Code Playgroud)
所以这实际上只是打印出选择查询返回的列名。
我必须编写什么代码才能返回表中的行数?我很遗憾使用 peewee,因为它使得本来应该是简单的查询变得不可能找到正确的语法。
Peewee 惰性地评估查询,因此您需要将其强制到列表或迭代它以检索结果,例如
query = User.select(User, fn.Count(Tweet.id).alias('num_tweets'))
for user in query:
print user.username, user.num_tweets
users = list(query)
Run Code Online (Sandbox Code Playgroud)