Ticket #11981: 11981.q_filter_exclude.diff

File 11981.q_filter_exclude.diff, 1.9 KB (added by Johannes Dollinger, 15 years ago)
  • django/db/models/query.py

     
    508508        if args or kwargs:
    509509            assert self.query.can_filter(), \
    510510                    "Cannot filter a query once a slice has been taken."
    511 
     511        if not kwargs and len(args) == 1 and hasattr(args[0], 'add_to_query'):
     512            q = args[0]
     513        else:
     514            q = Q(*args, **kwargs)
     515        if negate:
     516            q = ~q
    512517        clone = self._clone()
    513         if negate:
    514             clone.query.add_q(~Q(*args, **kwargs))
    515         else:
    516             clone.query.add_q(Q(*args, **kwargs))
     518        clone.query.add_q(q)
    517519        return clone
    518520
    519521    def complex_filter(self, filter_obj):
  • tests/modeltests/or_lookups/models.py

     
    2525
    2626    def __unicode__(self):
    2727        return self.headline
     28       
     29class HeadlineContainsQ(object):
     30    def __init__(self, substr, negated=False):
     31        self.substr = substr
     32        self.negated = negated
    2833
     34    def add_to_query(self, query, aliases=None):
     35        q = models.Q(headline__icontains=self.substr)
     36        if self.negated:
     37            q = ~q
     38        query.add_q(q)
     39       
     40    def __invert__(self):
     41        return self.__class__(self.substr, not self.negated)
     42
    2943__test__ = {'API_TESTS':"""
    3044>>> from datetime import datetime
    3145>>> from django.db.models import Q
     
    133147[<Article: Hello>]
    134148>>> Article.objects.complex_filter(Q(pk=1) | Q(pk=2))
    135149[<Article: Hello>, <Article: Goodbye>]
     150
     151>>> Article.objects.filter(HeadlineContainsQ("good"))
     152[<Article: Goodbye>, <Article: Hello and goodbye>]
     153>>> Article.objects.exclude(HeadlineContainsQ("good"))
     154[<Article: Hello>]
    136155"""}
Back to Top