SQL Functions

SQL functions, like COUNT() or SUM(), can be expressed using the fn() helper:

  1. # Get all users and the number of tweets they've authored. Sort the
  2. # results from most tweets -> fewest tweets.
  3. query = (User
  4. .select(User, fn.COUNT(Tweet.id).alias('tweet_count'))
  5. .join(Tweet, JOIN.LEFT_OUTER)
  6. .group_by(User)
  7. .order_by(fn.COUNT(Tweet.id).desc()))
  8. for user in query:
  9. print('%s -- %s tweets' % (user.username, user.tweet_count))

The fn helper exposes any SQL function as if it were a method. The parameters can be fields, values, subqueries, or even nested functions.

Nesting function calls

Suppose you need to want to get a list of all users whose username begins with a. There are a couple ways to do this, but one method might be to use some SQL functions like LOWER and SUBSTR. To use arbitrary SQL functions, use the special fn() object to construct queries:

  1. # Select the user's id, username and the first letter of their username, lower-cased
  2. first_letter = fn.LOWER(fn.SUBSTR(User.username, 1, 1))
  3. query = User.select(User, first_letter.alias('first_letter'))
  4. # Alternatively we could select only users whose username begins with 'a'
  5. a_users = User.select().where(first_letter == 'a')
  6. >>> for user in a_users:
  7. ... print(user.username)