Adding user-defined operators

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

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. def mod(lhs, rhs):
  4. 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_ext module, as it contains numerous operators specific to postgresql’s hstore.