如何在Peewee ORM中使用fn对象

阿尔梅尔

我正在使用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 []

因此,这实际上只是打印出由select查询返回的列名。

我必须写什么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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章