Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
"""
|
|
|
|
Various data structures used in query construction.
|
|
|
|
|
2009-03-19 17:06:04 +08:00
|
|
|
Factored out from django.db.models.query to avoid making the main module very
|
|
|
|
large and/or so that they can be used by other modules without getting into
|
|
|
|
circular import difficulties.
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
"""
|
2017-05-19 02:03:30 +08:00
|
|
|
import copy
|
2017-01-19 04:30:21 +08:00
|
|
|
import functools
|
2015-08-03 10:30:06 +08:00
|
|
|
import inspect
|
2013-11-09 20:25:15 +08:00
|
|
|
from collections import namedtuple
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2015-04-17 22:25:11 +08:00
|
|
|
from django.utils import tree
|
2009-03-19 17:06:04 +08:00
|
|
|
|
2013-11-09 20:25:15 +08:00
|
|
|
# PathInfo is used when converting lookups (fk__somecol). The contents
|
|
|
|
# describe the relation in Model terms (model Options and Fields for both
|
|
|
|
# sides of the relation. The join_field is the field backing the relation.
|
2017-09-22 23:53:17 +08:00
|
|
|
PathInfo = namedtuple('PathInfo', 'from_opts to_opts target_fields join_field m2m direct filtered_relation')
|
2013-11-09 20:25:15 +08:00
|
|
|
|
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
class InvalidQuery(Exception):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""The query passed to raw() isn't a safe query to use with raw()."""
|
2009-12-20 10:46:58 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
2016-08-12 02:16:48 +08:00
|
|
|
def subclasses(cls):
|
|
|
|
yield cls
|
|
|
|
for subclass in cls.__subclasses__():
|
2017-01-22 09:02:00 +08:00
|
|
|
yield from subclasses(subclass)
|
2016-08-12 02:16:48 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class QueryWrapper:
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
"""
|
|
|
|
A type that indicates the contents are an SQL fragment and the associate
|
|
|
|
parameters. Can be used to pass opaque data to a where-clause, for example.
|
|
|
|
"""
|
2014-12-23 21:16:56 +08:00
|
|
|
contains_aggregate = False
|
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def __init__(self, sql, params):
|
2013-02-10 23:15:49 +08:00
|
|
|
self.data = sql, list(params)
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
|
2014-11-16 09:56:42 +08:00
|
|
|
def as_sql(self, compiler=None, connection=None):
|
2009-01-29 18:46:36 +08:00
|
|
|
return self.data
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
class Q(tree.Node):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Encapsulate filters as objects that can then be combined logically (using
|
2016-02-18 21:44:53 +08:00
|
|
|
`&` and `|`).
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
"""
|
|
|
|
# Connection types
|
|
|
|
AND = 'AND'
|
|
|
|
OR = 'OR'
|
|
|
|
default = AND
|
2017-12-08 23:59:49 +08:00
|
|
|
conditional = True
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
|
2018-10-09 03:06:02 +08:00
|
|
|
def __init__(self, *args, _connector=None, _negated=False, **kwargs):
|
|
|
|
super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
|
|
|
|
def _combine(self, other, conn):
|
|
|
|
if not isinstance(other, Q):
|
|
|
|
raise TypeError(other)
|
2017-05-19 02:03:30 +08:00
|
|
|
|
|
|
|
# If the other Q() is empty, ignore it and just use `self`.
|
|
|
|
if not other:
|
|
|
|
return copy.deepcopy(self)
|
|
|
|
# Or if this Q is empty, ignore it and just use `other`.
|
|
|
|
elif not self:
|
|
|
|
return copy.deepcopy(other)
|
|
|
|
|
2010-03-27 23:16:27 +08:00
|
|
|
obj = type(self)()
|
Refactored qs.add_q() and utils/tree.py
The sql/query.py add_q method did a lot of where/having tree hacking to
get complex queries to work correctly. The logic was refactored so that
it should be simpler to understand. The new logic should also produce
leaner WHERE conditions.
The changes cascade somewhat, as some other parts of Django (like
add_filter() and WhereNode) expect boolean trees in certain format or
they fail to work. So to fix the add_q() one must fix utils/tree.py,
some things in add_filter(), WhereNode and so on.
This commit also fixed add_filter to see negate clauses up the path.
A query like .exclude(Q(reversefk__in=a_list)) didn't work similarly to
.filter(~Q(reversefk__in=a_list)). The reason for this is that only
the immediate parent negate clauses were seen by add_filter, and thus a
tree like AND: (NOT AND: (AND: condition)) will not be handled
correctly, as there is one intermediary AND node in the tree. The
example tree is generated by .exclude(~Q(reversefk__in=a_list)).
Still, aggregation lost connectors in OR cases, and F() objects and
aggregates in same filter clause caused GROUP BY problems on some
databases.
Fixed #17600, fixed #13198, fixed #17025, fixed #17000, fixed #11293.
2012-05-25 05:27:24 +08:00
|
|
|
obj.connector = conn
|
2010-03-27 23:16:27 +08:00
|
|
|
obj.add(self, conn)
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
obj.add(other, conn)
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def __or__(self, other):
|
|
|
|
return self._combine(other, self.OR)
|
|
|
|
|
|
|
|
def __and__(self, other):
|
|
|
|
return self._combine(other, self.AND)
|
|
|
|
|
|
|
|
def __invert__(self):
|
2010-03-27 23:16:27 +08:00
|
|
|
obj = type(self)()
|
|
|
|
obj.add(self, self.AND)
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
obj.negate()
|
|
|
|
return obj
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2015-05-11 15:02:41 +08:00
|
|
|
# We must promote any new joins to left outer joins so that when Q is
|
|
|
|
# used as an expression, rows aren't filtered due to joins.
|
2015-05-19 19:49:00 +08:00
|
|
|
clause, joins = query._add_q(self, reuse, allow_joins=allow_joins, split_subq=False)
|
2015-06-05 22:48:57 +08:00
|
|
|
query.promote_joins(joins)
|
2015-01-02 09:39:31 +08:00
|
|
|
return clause
|
|
|
|
|
2016-11-06 18:37:07 +08:00
|
|
|
def deconstruct(self):
|
|
|
|
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
|
2018-02-13 03:20:54 +08:00
|
|
|
if path.startswith('django.db.models.query_utils'):
|
|
|
|
path = path.replace('django.db.models.query_utils', 'django.db.models')
|
2016-11-06 18:37:07 +08:00
|
|
|
args, kwargs = (), {}
|
|
|
|
if len(self.children) == 1 and not isinstance(self.children[0], Q):
|
|
|
|
child = self.children[0]
|
|
|
|
kwargs = {child[0]: child[1]}
|
|
|
|
else:
|
|
|
|
args = tuple(self.children)
|
2018-02-13 03:20:54 +08:00
|
|
|
if self.connector != self.default:
|
|
|
|
kwargs = {'_connector': self.connector}
|
2016-11-06 18:37:07 +08:00
|
|
|
if self.negated:
|
|
|
|
kwargs['_negated'] = True
|
|
|
|
return path, args, kwargs
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class DeferredAttribute:
|
2009-03-19 17:06:04 +08:00
|
|
|
"""
|
|
|
|
A wrapper for a deferred-loading field. When the value is read from this
|
|
|
|
object the first time, the query is executed.
|
|
|
|
"""
|
2019-07-23 20:04:06 +08:00
|
|
|
def __init__(self, field):
|
|
|
|
self.field = field
|
2009-03-19 17:06:04 +08:00
|
|
|
|
2015-10-26 23:31:16 +08:00
|
|
|
def __get__(self, instance, cls=None):
|
2009-03-19 17:06:04 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Retrieve and caches the value from the datastore on the first lookup.
|
|
|
|
Return the cached value.
|
2009-03-19 17:06:04 +08:00
|
|
|
"""
|
2016-02-02 17:33:09 +08:00
|
|
|
if instance is None:
|
|
|
|
return self
|
2009-04-04 11:21:31 +08:00
|
|
|
data = instance.__dict__
|
2019-07-23 20:04:06 +08:00
|
|
|
field_name = self.field.attname
|
|
|
|
if data.get(field_name, self) is self:
|
2013-04-26 00:42:08 +08:00
|
|
|
# Let's see if the field is part of the parent chain. If so we
|
2012-05-27 07:08:44 +08:00
|
|
|
# might be able to reuse the already loaded value. Refs #18343.
|
2019-07-23 20:04:06 +08:00
|
|
|
val = self._check_parent_chain(instance)
|
2012-05-27 07:08:44 +08:00
|
|
|
if val is None:
|
2019-07-23 20:04:06 +08:00
|
|
|
instance.refresh_from_db(fields=[field_name])
|
|
|
|
val = getattr(instance, field_name)
|
|
|
|
data[field_name] = val
|
|
|
|
return data[field_name]
|
2009-04-04 11:21:31 +08:00
|
|
|
|
2019-07-23 20:04:06 +08:00
|
|
|
def _check_parent_chain(self, instance):
|
2012-05-27 07:08:44 +08:00
|
|
|
"""
|
2012-07-21 03:14:27 +08:00
|
|
|
Check if the field value can be fetched from a parent field already
|
2012-05-27 07:08:44 +08:00
|
|
|
loaded in the instance. This can be done if the to-be fetched
|
|
|
|
field is a primary key field.
|
|
|
|
"""
|
|
|
|
opts = instance._meta
|
2019-07-23 20:04:06 +08:00
|
|
|
link_field = opts.get_ancestor_link(self.field.model)
|
|
|
|
if self.field.primary_key and self.field != link_field:
|
2012-05-27 07:08:44 +08:00
|
|
|
return getattr(instance, link_field.attname)
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class RegisterLookupMixin:
|
2016-08-12 02:16:48 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _get_lookup(cls, lookup_name):
|
|
|
|
return cls.get_lookups().get(lookup_name, None)
|
|
|
|
|
|
|
|
@classmethod
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache(maxsize=None)
|
2016-08-12 02:16:48 +08:00
|
|
|
def get_lookups(cls):
|
|
|
|
class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
|
|
|
|
return cls.merge_dicts(class_lookups)
|
2015-08-03 10:30:06 +08:00
|
|
|
|
|
|
|
def get_lookup(self, lookup_name):
|
|
|
|
from django.db.models.lookups import Lookup
|
|
|
|
found = self._get_lookup(lookup_name)
|
|
|
|
if found is None and hasattr(self, 'output_field'):
|
|
|
|
return self.output_field.get_lookup(lookup_name)
|
|
|
|
if found is not None and not issubclass(found, Lookup):
|
|
|
|
return None
|
|
|
|
return found
|
|
|
|
|
|
|
|
def get_transform(self, lookup_name):
|
|
|
|
from django.db.models.lookups import Transform
|
|
|
|
found = self._get_lookup(lookup_name)
|
|
|
|
if found is None and hasattr(self, 'output_field'):
|
|
|
|
return self.output_field.get_transform(lookup_name)
|
|
|
|
if found is not None and not issubclass(found, Transform):
|
|
|
|
return None
|
|
|
|
return found
|
|
|
|
|
2016-08-12 02:16:48 +08:00
|
|
|
@staticmethod
|
|
|
|
def merge_dicts(dicts):
|
|
|
|
"""
|
|
|
|
Merge dicts in reverse to preference the order of the original list. e.g.,
|
|
|
|
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
|
|
|
|
"""
|
|
|
|
merged = {}
|
|
|
|
for d in reversed(dicts):
|
|
|
|
merged.update(d)
|
|
|
|
return merged
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _clear_cached_lookups(cls):
|
|
|
|
for subclass in subclasses(cls):
|
|
|
|
subclass.get_lookups.cache_clear()
|
|
|
|
|
2015-08-03 10:30:06 +08:00
|
|
|
@classmethod
|
|
|
|
def register_lookup(cls, lookup, lookup_name=None):
|
|
|
|
if lookup_name is None:
|
|
|
|
lookup_name = lookup.lookup_name
|
|
|
|
if 'class_lookups' not in cls.__dict__:
|
|
|
|
cls.class_lookups = {}
|
|
|
|
cls.class_lookups[lookup_name] = lookup
|
2016-08-12 02:16:48 +08:00
|
|
|
cls._clear_cached_lookups()
|
2015-08-03 10:30:06 +08:00
|
|
|
return lookup
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _unregister_lookup(cls, lookup, lookup_name=None):
|
|
|
|
"""
|
|
|
|
Remove given lookup from cls lookups. For use in tests only as it's
|
|
|
|
not thread-safe.
|
|
|
|
"""
|
|
|
|
if lookup_name is None:
|
|
|
|
lookup_name = lookup.lookup_name
|
|
|
|
del cls.class_lookups[lookup_name]
|
|
|
|
|
|
|
|
|
2012-06-26 23:08:42 +08:00
|
|
|
def select_related_descend(field, restricted, requested, load_fields, reverse=False):
|
2008-06-29 17:40:17 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return True if this field should be used to descend deeper for
|
2008-06-29 17:40:17 +08:00
|
|
|
select_related() purposes. Used by both the query construction code
|
|
|
|
(sql.query.fill_related_selections()) and the model instance creation code
|
2012-06-26 23:08:42 +08:00
|
|
|
(query.get_klass_info()).
|
2010-01-27 21:30:29 +08:00
|
|
|
|
|
|
|
Arguments:
|
|
|
|
* field - the field to be checked
|
|
|
|
* restricted - a boolean field, indicating if the field list has been
|
|
|
|
manually restricted using a requested clause)
|
|
|
|
* requested - The select_related() dictionary.
|
2012-06-26 23:08:42 +08:00
|
|
|
* load_fields - the set of fields to be loaded on this model
|
2010-01-27 21:30:29 +08:00
|
|
|
* reverse - boolean, True if we are checking a reverse select related
|
2008-06-29 17:40:17 +08:00
|
|
|
"""
|
2015-02-26 22:19:17 +08:00
|
|
|
if not field.remote_field:
|
2008-06-29 17:40:17 +08:00
|
|
|
return False
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field.parent_link and not reverse:
|
2008-06-29 17:40:17 +08:00
|
|
|
return False
|
2010-01-27 21:30:29 +08:00
|
|
|
if restricted:
|
|
|
|
if reverse and field.related_query_name() not in requested:
|
|
|
|
return False
|
|
|
|
if not reverse and field.name not in requested:
|
|
|
|
return False
|
2008-06-29 17:40:17 +08:00
|
|
|
if not restricted and field.null:
|
|
|
|
return False
|
2012-06-26 23:08:42 +08:00
|
|
|
if load_fields:
|
2014-12-01 15:28:01 +08:00
|
|
|
if field.attname not in load_fields:
|
2012-06-26 23:08:42 +08:00
|
|
|
if restricted and field.name in requested:
|
|
|
|
raise InvalidQuery("Field %s.%s cannot be both deferred"
|
|
|
|
" and traversed using select_related"
|
|
|
|
" at the same time." %
|
|
|
|
(field.model._meta.object_name, field.name))
|
2008-06-29 17:40:17 +08:00
|
|
|
return True
|
2009-03-19 17:06:04 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2015-02-02 19:48:30 +08:00
|
|
|
def refs_expression(lookup_parts, annotations):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Check if the lookup_parts contains references to the given annotations set.
|
|
|
|
Because the LOOKUP_SEP is contained in the default annotation names, check
|
|
|
|
each prefix of the lookup_parts for a match.
|
2015-02-02 19:48:30 +08:00
|
|
|
"""
|
2017-07-28 20:42:52 +08:00
|
|
|
for n in range(1, len(lookup_parts) + 1):
|
2015-02-02 19:48:30 +08:00
|
|
|
level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
|
|
|
|
if level_n_lookup in annotations and annotations[level_n_lookup]:
|
|
|
|
return annotations[level_n_lookup], lookup_parts[n:]
|
|
|
|
return False, ()
|
2015-06-25 23:31:07 +08:00
|
|
|
|
|
|
|
|
|
|
|
def check_rel_lookup_compatibility(model, target_opts, field):
|
|
|
|
"""
|
|
|
|
Check that self.model is compatible with target_opts. Compatibility
|
|
|
|
is OK if:
|
|
|
|
1) model and opts match (where proxy inheritance is removed)
|
|
|
|
2) model is parent of opts' model or the other way around
|
|
|
|
"""
|
|
|
|
def check(opts):
|
|
|
|
return (
|
|
|
|
model._meta.concrete_model == opts.concrete_model or
|
|
|
|
opts.concrete_model in model._meta.get_parent_list() or
|
|
|
|
model in opts.get_parent_list()
|
|
|
|
)
|
|
|
|
# If the field is a primary key, then doing a query against the field's
|
|
|
|
# model is ok, too. Consider the case:
|
|
|
|
# class Restaurant(models.Model):
|
2019-04-03 14:18:54 +08:00
|
|
|
# place = OneToOneField(Place, primary_key=True):
|
2015-06-25 23:31:07 +08:00
|
|
|
# Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
|
|
|
|
# If we didn't have the primary key check, then pk__in (== place__in) would
|
|
|
|
# give Place's opts as the target opts, but Restaurant isn't compatible
|
|
|
|
# with that. This logic applies only to primary keys, as when doing __in=qs,
|
|
|
|
# we are going to turn this into __in=qs.values('pk') later on.
|
|
|
|
return (
|
|
|
|
check(target_opts) or
|
|
|
|
(getattr(field, 'primary_key', False) and check(field.model._meta))
|
|
|
|
)
|
2017-09-22 23:53:17 +08:00
|
|
|
|
|
|
|
|
|
|
|
class FilteredRelation:
|
|
|
|
"""Specify custom filtering in the ON clause of SQL joins."""
|
|
|
|
|
|
|
|
def __init__(self, relation_name, *, condition=Q()):
|
|
|
|
if not relation_name:
|
|
|
|
raise ValueError('relation_name cannot be empty.')
|
|
|
|
self.relation_name = relation_name
|
|
|
|
self.alias = None
|
|
|
|
if not isinstance(condition, Q):
|
|
|
|
raise ValueError('condition argument must be a Q() instance.')
|
|
|
|
self.condition = condition
|
|
|
|
self.path = []
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return (
|
|
|
|
isinstance(other, self.__class__) and
|
|
|
|
self.relation_name == other.relation_name and
|
|
|
|
self.alias == other.alias and
|
|
|
|
self.condition == other.condition
|
|
|
|
)
|
|
|
|
|
|
|
|
def clone(self):
|
|
|
|
clone = FilteredRelation(self.relation_name, condition=self.condition)
|
|
|
|
clone.alias = self.alias
|
|
|
|
clone.path = self.path[:]
|
|
|
|
return clone
|
|
|
|
|
|
|
|
def resolve_expression(self, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
QuerySet.annotate() only accepts expression-like arguments
|
|
|
|
(with a resolve_expression() method).
|
|
|
|
"""
|
|
|
|
raise NotImplementedError('FilteredRelation.resolve_expression() is unused.')
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
# Resolve the condition in Join.filtered_relation.
|
|
|
|
query = compiler.query
|
|
|
|
where = query.build_filtered_relation_q(self.condition, reuse=set(self.path))
|
|
|
|
return compiler.compile(where)
|