Search code examples
pythondjangolookupmodulo

Django custom lookup, error on using modulus operation in as_sql()


from django.db.models import Lookup

class NotEqual(Lookup): lookup_name = 'div'

def as_sql(self, compiler, connection):
    lhs, lhs_param = self.process_lhs(compiler, connection)
    rhs, rhs_param = self.process_rhs(compiler, connection)
    params = lhs_param + rhs_param

    return "%s %% %s == 0" % (lhs, rhs), params

i am using

Book.objects.filter(rating__div=5)

Error

. . . File "D:\PROJECTS\Projects_Personal\django_challenges_venv_\Lib\site-packages\MySQLdb\cursors.py", line 200, in _mogrify query = query % args ~~~~~~^~~~~~ ValueError: unsupported format character '%' (0x25) at index 272

this only happening with modulus operation with % operator, i can use MOD etc. but i wanted to know why with this operator this error happening. i tried to change this operator to other, they work fine but i didn't get anything for this not even in docs


Solution

  • This will go through formatting twice, once in the as_sql, and once by the cursor.

    As a result, you use four percentages:

    def as_sql(self, compiler, connection):
        lhs, lhs_param = self.process_lhs(compiler, connection)
        rhs, rhs_param = self.process_rhs(compiler, connection)
        params = lhs_param + rhs_param
        return '%s %%%% %s == 0' % (lhs, rhs), params

    another option is to inject the double precentages in the first formatting stage:

    def as_sql(self, compiler, connection):
        lhs, lhs_param = self.process_lhs(compiler, connection)
        rhs, rhs_param = self.process_rhs(compiler, connection)
        params = lhs_param + rhs_param
        return '%s %s %s == 0' % (lhs, '%%', rhs), params