Expressions

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

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

  • 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.  
  4. # user has logged in less than 5 times
  5. User.login_count < 5

Comparisons can be combined using bitwiseand and or. Operatorprecedence is controlled by python and comparisons can be nested to anarbitrary depth:

  1. # User is both and admin and has logged in today
  2. (User.is_admin == True) & (User.last_login >= today)
  3.  
  4. # User's username is either charlie or charles
  5. (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 comparedagainst 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!

Row values

Many databases support row values,which are similar to Python tuple objects. In Peewee, it is possible to userow-values in expressions via Tuple. For example,

  1. # If for some reason your schema stores dates in separate columns ("year",
  2. # "month" and "day"), you can use row-values to find all rows that happened
  3. # in a given month:
  4. Tuple(Event.year, Event.month) == (2019, 1)

The more common use for row-values is to compare against multiple columns froma subquery in a single expression. There are other ways to express these typesof queries, but row-values may offer a concise and readable approach.

For example, assume we have a table “EventLog” which contains an event type, anevent source, and some metadata. We also have an “IncidentLog”, which hasincident type, incident source, and metadata columns. We can use row-values tocorrelate incidents with certain events:

  1. class EventLog(Model):
  2. event_type = TextField()
  3. source = TextField()
  4. data = TextField()
  5. timestamp = TimestampField()
  6.  
  7. class IncidentLog(Model):
  8. incident_type = TextField()
  9. source = TextField()
  10. traceback = TextField()
  11. timestamp = TimestampField()
  12.  
  13. # Get a list of all the incident types and sources that have occured today.
  14. incidents = (IncidentLog
  15. .select(IncidentLog.incident_type, IncidentLog.source)
  16. .where(IncidentLog.timestamp >= datetime.date.today()))
  17.  
  18. # Find all events that correlate with the type and source of the
  19. # incidents that occured today.
  20. events = (EventLog
  21. .select()
  22. .where(Tuple(EventLog.event_type, EventLog.source).in_(incidents))
  23. .order_by(EventLog.timestamp))

Other ways to express this type of query would be to use a joinor to join on a subquery. The above example is therejust to give you and idea how Tuple might be used.

You can also use row-values to update multiple columns in a table, when the newdata is derived from a subquery. For an example, see here.