SQL Helper

There are times when you may want to simply pass in some arbitrary sql. You cando this using the special SQL class. One use-case is whenreferencing 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.  
  8. # Now we will order by the count, which was aliased to "ct"
  9. query = query.order_by(SQL('ct'))
  10.  
  11. # You could, of course, also write this as:
  12. query = query.order_by(fn.COUNT(Tweet.id))

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