You can also use + and - prefix operators to indicate ordering:

    1. # The following queries are equivalent:
    2. Tweet.select().order_by(Tweet.created_date.desc())
    3. Tweet.select().order_by(-Tweet.created_date) # Note the "-" prefix.
    4. # Similarly you can use "+" to indicate ascending order, though ascending
    5. # is the default when no ordering is otherwise specified.
    1. SELECT t1."id", t1."user_id", t1."message", t1."is_published", t1."created_date"
    2. FROM "tweet" AS t1
    3. INNER JOIN "user" AS t2
    4. ON t1."user_id" = t2."id"
    5. ORDER BY t2."username", t1."created_date" DESC

    When sorting on a calculated value, you can either include the necessary SQL expressions, or reference the alias assigned to the value. Here are two examples illustrating these methods:

    1. query = (User
    2. .select(User.username, fn.COUNT(Tweet.id).alias('num_tweets'))
    3. .group_by(User.username)
    4. .order_by(fn.COUNT(Tweet.id).desc()))

    Alternatively, you can reference the alias assigned to the calculated value in the select clause. This method has the benefit of being a bit easier to read. Note that we are not referring to the named alias directly, but are wrapping it using the helper:

    1. ntweets = fn.COUNT(Tweet.id)
    2. query = (User
    3. .select(User.username, ntweets.alias('num_tweets'))
    4. .join(Tweet, JOIN.LEFT_OUTER)
    5. .group_by(User.username)