Posted on

Mod(modulo) operation is not officially defined for peewee database query. To use the “MOD“ operator, we have to override the operator by ourselves.1

from peewee import *
from peewee import Expression   # the building block for expressions
from peewee import OP


OP['MOD'] = 'mod'


def mod(lhs, rhs):
    return Expression(lhs, OP.MOD, rhs)

After this, we can use the mod function directly as a peewee SQL query expression.

audios = (Audio
          .select()
          .where(mod(Audio.id, n_checker) == checker_id)
          .order_by(fn.Rand())
          .limit(n_records)).execute()

References

  1. https://stackoverflow.com/questions/30141046/peewee-throws-keyerror-when-trying-to-add-user-defined-operator
  2. http://docs.peewee-orm.com/en/latest/peewee/query_operators.html

Leave a Reply

Your email address will not be published. Required fields are marked *