Peewee needs your help! Do you have suggestions on how the documentation could be improved? If so, please leave a comment on this GitHub issue:

    Query operators

    The following types of comparisons are supported by peewee:

    Because I ran out of operators to override, there are some additional query operations available as methods:

    Here is how you might use some of these query operators:

    Here is how you might combine expressions. Comparisons can be arbitrarily complex.

    Note

    Note that the actual comparisons are wrapped in parentheses. Python’s operator precedence necessitates that comparisons be wrapped in parentheses.

    1. # Find any users who are active administrations.
    2. User.select().where(
    3. (User.is_admin == True) &
    4. (User.is_active == True))
    5. # Find any users who are either administrators or super-users.
    6. User.select().where(
    7. (User.is_superuser == True))
    8. # Find any Tweets by users who are not admins (NOT IN).
    9. admins = User.select().where(User.is_admin == True)
    10. non_admin_tweets = Tweet.select().where(Tweet.user.not_in(admins))
    11. # Find any users who are not my friends (strangers).
    12. strangers = User.select().where(User.id.not_in(friends))

    Although you may be tempted to use python’s in, and, or and not operators in your query expressions, these will not work. The return value of an in expression is always coerced to a boolean value. Similarly, and, or and not all treat their arguments as boolean values and cannot be overloaded.

    So just remember:

    • Use .in_() and .not_in() instead of in and not in
    • Use & instead of and
    • Use | instead of or
    • Use ~ instead of not
    • Use .is_null() instead of is None or == None.
    • Don’t forget to wrap your comparisons in parentheses when using logical operators.

    For more examples, see the section.

    Note

    Because SQLite’s LIKE operation is case-insensitive by default, peewee will use the SQLite operation for case-sensitive searches. The glob operation uses asterisks for wildcards as opposed to the usual percent-sign. If you are using SQLite and want case-sensitive partial string matching, remember to use asterisks for the wildcard.