Skip to main content
 首页 » 编程设计

python之如何在 Peewee ORM 中使用 fn 对象

2024年10月25日10yyy_WW

我正在使用 Python 的 Peewee ORM 来处理 MySQL 数据库。 Peewee 提供了一个名为“fn”的对象,它允许您对数据库进行某些类型的调用。我想调用的其中一个电话如下:

Blocks.select(Blocks, fn.Count(Blocks.height)) 

其中 Blocks 是我数据库中的一个表,其中有一列名为 height。此语法直接取自 Peewee 的文档,即

User.select( 
User, fn.Count(Tweet.id)) 

位于此处 http://peewee.readthedocs.org/en/latest/peewee/querying.html .请注意,我的 python 文件顶部还有以下几行

import peewee 
from peewee import * 
from peewee import fn 

但是当我运行这段代码时,它不起作用,它吐出这个

<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 [] 

所以这实际上只是打印出选择查询返回的列名。

我必须编写什么 peewee 代码才能返回表中的行数?我对使用 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)