Created
December 1, 2015 22:39
-
-
Save tuatara/6188a4c7bacab1f52c80 to your computer and use it in GitHub Desktop.
Custom `length` lookup for Django ORM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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