Search code examples
pythonpeewee

How to use fn Object in Peewee ORM


I'm using Python's Peewee ORM to work with a MySQL database. Peewee supplies an object called "fn" that allows you to make certain types of calls to the database. One of those calls I want to make is the following:

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

Where Blocks is a table in my database, which has a column named height. This syntax is taken straight from Peewee's documentation, namely

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

located here http://peewee.readthedocs.org/en/latest/peewee/querying.html. Note that I also have the following lines at the top of my python file

import peewee
from peewee import *
from peewee import fn

Yet when I run this code, it doesn't work, and it spits out this

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

So this is really just printing out the column names that are returned by the select query.

What peewee code do I have to write to return the count of the number of rows in a table? I regret using peewee because it makes what should be simple queries impossibly hard to find the right syntax for.


Solution

  • Peewee lazily evaluates queries, so you need to coerce it to a list or iterate through it in order to retrieve results, e.g.

    query = User.select(User, fn.Count(Tweet.id).alias('num_tweets'))
    for user in query:
        print user.username, user.num_tweets
    users = list(query)