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:
- # We'll query the user table and annotate it with a count of tweets for
- # the given user
- query = (User
- .select(User, fn.Count(Tweet.id).alias('ct'))
- .join(Tweet)
- .group_by(User))
- # Now we will order by the count, which was aliased to "ct"
- query = query.order_by(SQL('ct'))
- # You could, of course, also write this as:
- query = query.order_by(fn.COUNT(Tweet.id))
There are two ways to execute hand-crafted SQL statements with peewee:
Database.execute_sql()
for executing any type of queryRawQuery
for executingSELECT
queries and returning modelinstances.