Skip to content

Instantly share code, notes, and snippets.

@tuatara
Created December 1, 2015 22:39
Show Gist options
  • Save tuatara/6188a4c7bacab1f52c80 to your computer and use it in GitHub Desktop.
Save tuatara/6188a4c7bacab1f52c80 to your computer and use it in GitHub Desktop.
Custom `length` lookup for Django ORM
class LengthLookup(models.Transform):
lookup_name = 'length'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'CHAR_LENGTH(%s)' % lhs, params
# SQLite doesn't implement CHAR_LENGTH, but its implementation of LENGTH conforms
# with standard SQL CHAR_LENGTH (i.e. number of chars, not number of bytes)
def as_sqlite(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'LENGTH(%s)' % lhs, params
@property
def output_field(self):
return models.IntegerField()
models.CharField.register_lookup(LengthLookup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment