Created
December 20, 2014 08:44
-
-
Save jarshwah/a541857db195f0486b9e to your computer and use it in GitHub Desktop.
Making func expressions into Transforms
This file contains 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
diff --git django/db/models/functions.py django/db/models/functions.py | |
index c3dea1f..30046ea 100644 | |
--- django/db/models/functions.py | |
+++ django/db/models/functions.py | |
@@ -2,7 +2,7 @@ | |
Classes that represent database functions. | |
""" | |
from django.db.models.expressions import Func, Value | |
-from django.db.models import IntegerField | |
+from django.db.models import IntegerField, Transform | |
class Coalesce(Func): | |
@@ -69,11 +69,14 @@ class Concat(Func): | |
return ConcatPair(expressions[0], self._paired(expressions[1:])) | |
-class Length(Func): | |
+class Length(Func, Transform): | |
"""Returns the number of characters in the expression""" | |
function = 'LENGTH' | |
+ lookup_name = 'length' | |
- def __init__(self, expression, **extra): | |
+ def __init__(self, expression, lookups=None, **extra): | |
+ if lookups is not None: | |
+ self.init_lookups = lookups[:] | |
output_field = extra.pop('output_field', IntegerField()) | |
super(Length, self).__init__(expression, output_field=output_field, **extra) | |
@@ -81,6 +84,10 @@ class Length(Func): | |
self.function = 'CHAR_LENGTH' | |
return super(Length, self).as_sql(compiler, connection) | |
+ @property | |
+ def lhs(self): | |
+ return self.get_source_expressions()[0] | |
+ | |
class Lower(Func): | |
function = 'LOWER' | |
diff --git tests/functions/tests.py tests/functions/tests.py | |
index 32e0970..0fcd59e 100644 | |
--- tests/functions/tests.py | |
+++ tests/functions/tests.py | |
@@ -157,6 +157,20 @@ class FunctionTests(TestCase): | |
authors.filter(alias_length__lte=Length('name')).count(), | |
1) | |
+ def test_length_transform(self): | |
+ try: | |
+ CharField.register_lookup(Length) | |
+ Author.objects.create(name='John Smith', alias='smithj') | |
+ Author.objects.create(name='Rhonda') | |
+ authors = Author.objects.filter(name__length__gt=7) | |
+ self.assertQuerysetEqual( | |
+ authors.order_by('name'), [ | |
+ 'John Smith' | |
+ ], | |
+ lambda a: a.name) | |
+ finally: | |
+ CharField._unregister_lookup(Length) | |
+ | |
def test_substr(self): | |
Author.objects.create(name='John Smith', alias='smithj') | |
Author.objects.create(name='Rhonda') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment