Expressions

Peewee is designed to provide a simple, expressive, and pythonic way of constructing SQL queries. This section will provide a quick overview of some common types of expressions.

There are two primary types of objects that can be composed to create expressions:

  • Field instances
  • SQL aggregations and functions using fn

We will assume a simple “User” model with fields for username and other things. It looks like this:

  1. class User(Model):
  2. username = CharField()
  3. is_admin = BooleanField()
  4. is_active = BooleanField()
  5. last_login = DateTimeField()
  6. login_count = IntegerField()
  7. failed_logins = IntegerField()

Comparisons use the query-operators:

  1. # username is equal to 'charlie'
  2. User.username == 'charlie'
  3. # user has logged in less than 5 times
  4. User.login_count < 5

Comparisons can be combined using bitwise and and or. Operator precedence is controlled by python and comparisons can be nested to an arbitrary depth:

  1. # User is both and admin and has logged in today
  2. (User.is_admin == True) & (User.last_login >= today)
  3. # User's username is either charlie or charles
  4. (User.username == 'charlie') | (User.username == 'charles')

Comparisons can be used with functions as well:

  1. # user's username starts with a 'g' or a 'G':
  2. fn.Lower(fn.Substr(User.username, 1, 1)) == 'g'

We can do some fairly interesting things, as expressions can be compared against other expressions. Expressions also support arithmetic operations:

  1. # users who entered the incorrect more than half the time and have logged
  2. # in at least 10 times
  3. (User.failed_logins > (User.login_count * .5)) & (User.login_count > 10)

Expressions allow us to do atomic updates:

  1. # when a user logs in we want to increment their login count:
  2. User.update(login_count=User.login_count + 1).where(User.id == user_id)

Expressions can be used in all parts of a query, so experiment!