SQL Helper

There are times when you may want to simply pass in some arbitrary sql. You can do this using the special SQL class. One use-case is when referencing an alias:

  1. # We'll query the user table and annotate it with a count of tweets for
  2. # the given user
  3. query = (User
  4. .select(User, fn.Count(Tweet.id).alias('ct'))
  5. .join(Tweet)
  6. .group_by(User))
  7. # Now we will order by the count, which was aliased to "ct"
  8. query = query.order_by(SQL('ct'))
  9. # You could, of course, also write this as:
  10. query = query.order_by(fn.COUNT(Tweet.id))

There are two ways to execute hand-crafted SQL statements with peewee:

  1. Database.execute_sql() for executing any type of query
  2. RawQuery for executing SELECT queries and returning model instances.