diff --git a/AUTHORS b/AUTHORS index ef00671540..af350240b1 100644 --- a/AUTHORS +++ b/AUTHORS @@ -662,6 +662,7 @@ answer newbie questions, and generally made Django that much better: pradeep.gowda@gmail.com Preston Holmes Preston Timmons + Priyansh Saxena Rachel Tobin Rachel Willmer Radek Švarz diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index f7b1baad3a..2968e2cfee 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -65,6 +65,9 @@ class Combinable: # OPERATORS # ############# + def __neg__(self): + return self._combine(-1, self.MUL, False) + def __add__(self, other): return self._combine(other, self.ADD, False) diff --git a/docs/ref/models/expressions.txt b/docs/ref/models/expressions.txt index fcd88a58a2..8ca975cc3a 100644 --- a/docs/ref/models/expressions.txt +++ b/docs/ref/models/expressions.txt @@ -13,9 +13,13 @@ more complex computations. Supported arithmetic ==================== -Django supports addition, subtraction, multiplication, division, modulo -arithmetic, and the power operator on query expressions, using Python constants, -variables, and even other expressions. +Django supports negation, addition, subtraction, multiplication, division, +modulo arithmetic, and the power operator on query expressions, using Python +constants, variables, and even other expressions. + +.. versionchanged:: 2.1 + + Support for negation was added. Some examples ============= diff --git a/docs/releases/2.1.txt b/docs/releases/2.1.txt index a2aa2e8379..f1c3011c9d 100644 --- a/docs/releases/2.1.txt +++ b/docs/releases/2.1.txt @@ -178,6 +178,8 @@ Models :class:`~django.db.models.DateField` and :class:`~django.db.models.DateTimeField` to the Monday of a week. +* Query expressions can now be negated using a minus sign. + Requests and Responses ~~~~~~~~~~~~~~~~~~~~~~ diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index 2a6714a65f..218e540bd9 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -1425,6 +1425,10 @@ class ReprTests(TestCase): class CombinableTests(SimpleTestCase): bitwise_msg = 'Use .bitand() and .bitor() for bitwise logical operations.' + def test_negation(self): + c = Combinable() + self.assertEqual(-c, c * -1) + def test_and(self): with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg): Combinable() & Combinable()