Adding user-defined operators

Because I ran out of python operators to overload, there are some missingoperators in peewee, for instance modulo. If you find that you need tosupport an operator that is not in the table above, it is very easy to add yourown.

Here is how you might add support for modulo in SQLite:

  1. from peewee import *
  2. from peewee import Expression # the building block for expressions
  3.  
  4. def mod(lhs, rhs):
  5. return Expression(lhs, '%', rhs)

Now you can use these custom operators to build richer queries:

  1. # Users with even ids.
  2. User.select().where(mod(User.id, 2) == 0)

For more examples check out the source to the playhouse.postgresql_extmodule, as it contains numerous operators specific to postgresql’s hstore.