Ticket #17186: invert.f-2.patch

File invert.f-2.patch, 2.5 KB (added by Andrei Antoukh, 13 years ago)
  • tests/modeltests/expressions/tests.py

     
    2222            ceo=Employee.objects.create(firstname="Max", lastname="Mustermann")
    2323        )
    2424
     25        # mark acttive employees when their companys have num_chairs great that 3
     26        employee_qs = Employee.objects.filter(is_active=False)
     27        self.assertEqual(employee_qs.count(), 3)
     28
     29        Employee.objects.filter(company_ceo_set__num_chairs__gte=3)\
     30            .update(is_active=~F("is_active"))
     31
     32        employee_qs = Employee.objects.filter(is_active=False)
     33        self.assertEqual(employee_qs.count(), 1)
     34
    2535        company_query = Company.objects.values(
    2636            "name", "num_employees", "num_chairs"
    2737        ).order_by(
  • tests/modeltests/expressions/models.py

     
    88class Employee(models.Model):
    99    firstname = models.CharField(max_length=50)
    1010    lastname = models.CharField(max_length=50)
     11    is_active = models.BooleanField(default=False)
    1112
    1213    def __unicode__(self):
    1314        return u'%s %s' % (self.firstname, self.lastname)
     
    2627
    2728    def __unicode__(self):
    2829        return self.name
     30
     31
  • django/db/models/expressions.py

    +
     
    9898    """
    9999    An expression representing the value of the given field.
    100100    """
     101
     102    _invert = False
     103
    101104    def __init__(self, name):
    102105        super(F, self).__init__(None, None, False)
    103106        self.name = name
     
    107110        obj.name = self.name
    108111        return obj
    109112
     113    def __invert__(self):
     114        self._invert = True
     115        return self
     116
    110117    def prepare(self, evaluator, query, allow_joins):
    111118        return evaluator.prepare_leaf(self, query, allow_joins)
    112119
    113120    def evaluate(self, evaluator, qn, connection):
    114         return evaluator.evaluate_leaf(self, qn, connection)
     121        evresult = list(evaluator.evaluate_leaf(self, qn, connection))
     122        if self._invert:
     123            evresult[0] = "NOT %s" % evresult[0]
     124        return tuple(evresult)
    115125
     126
    116127class DateModifierNode(ExpressionNode):
    117128    """
    118129    Node that implements the following syntax:
Back to Top