Merged the queryset-refactor branch into trunk.
[fdr-django.git] / django / db / models / query_utils.py
blob0ce7900c74cbbff6eef80ee221ae43794a3e59fe
1 """
2 Various data structures used in query construction.
4 Factored out from django.db.models.query so that they can also be used by other
5 modules without getting into circular import difficulties.
6 """
8 from copy import deepcopy
10 from django.utils import tree
12 class QueryWrapper(object):
13 """
14 A type that indicates the contents are an SQL fragment and the associate
15 parameters. Can be used to pass opaque data to a where-clause, for example.
16 """
17 def __init__(self, sql, params):
18 self.data = sql, params
20 class Q(tree.Node):
21 """
22 Encapsulates filters as objects that can then be combined logically (using
23 & and |).
24 """
25 # Connection types
26 AND = 'AND'
27 OR = 'OR'
28 default = AND
30 def __init__(self, *args, **kwargs):
31 super(Q, self).__init__(children=list(args) + kwargs.items())
33 def _combine(self, other, conn):
34 if not isinstance(other, Q):
35 raise TypeError(other)
36 obj = deepcopy(self)
37 obj.add(other, conn)
38 return obj
40 def __or__(self, other):
41 return self._combine(other, self.OR)
43 def __and__(self, other):
44 return self._combine(other, self.AND)
46 def __invert__(self):
47 obj = deepcopy(self)
48 obj.negate()
49 return obj