Ticket #4858: 4858.2.patch

File 4858.2.patch, 2.5 KB (added by Collin Grady <cgrady@…>, 17 years ago)

added docs and tests

  • django/db/models/query.py

     
    752752    def __or__(self, other):
    753753        return QOr(self, other)
    754754
     755    def __invert__(self):
     756        return QNot(self)
     757
    755758    def get_sql(self, opts):
    756759        return parse_lookup(self.kwargs.items(), opts)
    757760
     
    761764        "Creates a negation of the q object passed in."
    762765        self.q = q
    763766
     767    def __invert__(self):
     768        "Returns the inner, non-negated q object"
     769        return self.q
     770
    764771    def get_sql(self, opts):
    765772        try:
    766773            joins, where, params = self.q.get_sql(opts)
  • tests/modeltests/or_lookups/models.py

     
    9292>>> Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello')
    9393[<Article: Hello and goodbye>]
    9494
     95# Q objects can be negated (NOT)
     96>>> Article.objects.filter(Q(pk=1) | ~Q(pk=2))
     97[<Article: Hello>, <Article: Hello and goodbye>]
     98
     99>>> Article.objects.filter(~Q(pk=1) & ~Q(pk=2))                                                                       
     100[<Article: Hello and goodbye>]
     101
     102# This allows for more complex queries than filter() and exclude() alone would allow
     103>>> Article.objects.filter(Q(pk=1) & (~Q(pk=2) | Q(pk=3)))                                                             
     104[<Article: Hello>]
     105
    95106# Try some arg queries with operations other than get_list
    96107>>> Article.objects.get(Q(headline__startswith='Hello'), Q(headline__contains='bye'))
    97108<Article: Hello and goodbye>
  • docs/db-api.txt

     
    14111411You can compose statements of arbitrary complexity by combining ``Q`` objects
    14121412with the ``&`` and ``|`` operators. You can also use parenthetical grouping.
    14131413
     1414``Q`` objects can also be negated using the ``~`` operator, allowing for ``OR``
     1415lookups that combine both a normal query and a negated (``NOT``) query::
     1416
     1417    Q(question__startswith='Who') | ~Q(pub_date__year=2005)
     1418
    14141419Each lookup function that takes keyword-arguments (e.g. ``filter()``,
    14151420``exclude()``, ``get()``) can also be passed one or more ``Q`` objects as
    14161421positional (not-named) arguments. If you provide multiple ``Q`` object
Back to Top