SQL Functions

SQL functions, like COUNT() or SUM(), can be expressed using thefn() 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. Theparameters 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 witha. There are a couple ways to do this, but one method might be to use someSQL functions like LOWER and SUBSTR. To use arbitrary SQL functions, usethe 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.  
  5. # Alternatively we could select only users whose username begins with 'a'
  6. a_users = User.select().where(first_letter == 'a')
  7.  
  8. >>> for user in a_users:
  9. ... print(user.username)