Skip to content

Instantly share code, notes, and snippets.

@patrys
Last active August 29, 2015 14:22
Show Gist options
  • Save patrys/45939463069613417a37 to your computer and use it in GitHub Desktop.
Save patrys/45939463069613417a37 to your computer and use it in GitHub Desktop.
Expression filter hack
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index 4306193..bf965c1 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -340,11 +340,27 @@ def reverse_ordering(self):
return self
+class ExpressionFilter(object):
+ def __init__(self, expression, value, lookup):
+ self.expression = expression
+ self.value = value
+ lookup = expression.get_lookup(lookup)
+ self.lookup = lookup
+
+ def resolve(self, query):
+ lhs = self.expression.resolve_expression(query)
+ return self.lookup(lhs, self.value)
+
+
class Expression(BaseExpression, Combinable):
"""
An expression that can be combined with other expressions.
"""
- pass
+ def __eq__(self, other):
+ return ExpressionFilter(self, other, 'exact')
+
+ def __lt__(self, other):
+ return ExpressionFilter(self, other, 'lt')
class CombinedExpression(Expression):
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index 88093d4..4c067df 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -16,7 +16,7 @@
from django.db import DEFAULT_DB_ALIAS, connections
from django.db.models.aggregates import Count
from django.db.models.constants import LOOKUP_SEP
-from django.db.models.expressions import Col, Ref
+from django.db.models.expressions import Col, Ref, ExpressionFilter
from django.db.models.fields.related_lookups import MultiColSource
from django.db.models.query_utils import Q, PathInfo, refs_expression
from django.db.models.sql.constants import (
@@ -1142,6 +1142,11 @@ def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
"""
if isinstance(filter_expr, dict):
raise FieldError("Cannot parse keyword query as dict")
+ if isinstance(filter_expr, ExpressionFilter):
+ clause = self.where_class()
+ condition = filter_expr.resolve(self)
+ clause.add(condition, AND)
+ return clause, []
arg, value = filter_expr
if not arg:
raise FieldError("Cannot parse keyword query %r" % arg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment