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
|
|
|
"""
|
|
|
|
Create SQL statements for QuerySets.
|
|
|
|
|
|
|
|
The code in here encapsulates all of the SQL construction so that QuerySets
|
|
|
|
themselves do not have to (and could be backed by things other than SQL
|
|
|
|
databases). The abstraction barrier only works one way: this module has to know
|
|
|
|
all about the internals of models in order to get the information it needs.
|
|
|
|
"""
|
2019-09-24 03:51:43 +08:00
|
|
|
import copy
|
2018-09-29 15:22:27 +08:00
|
|
|
import difflib
|
2017-06-18 23:53:40 +08:00
|
|
|
import functools
|
2019-04-05 12:37:58 +08:00
|
|
|
import sys
|
2019-02-05 19:22:08 +08:00
|
|
|
from collections import Counter, namedtuple
|
2018-02-06 00:42:47 +08:00
|
|
|
from collections.abc import Iterator, Mapping
|
2015-01-28 20:35:27 +08:00
|
|
|
from itertools import chain, count, product
|
|
|
|
from string import ascii_uppercase
|
2011-09-10 03:22:28 +08:00
|
|
|
|
2020-11-04 05:50:10 +08:00
|
|
|
from django.core.exceptions import FieldDoesNotExist, FieldError
|
2017-09-18 21:42:29 +08:00
|
|
|
from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections
|
2013-11-09 20:25:15 +08:00
|
|
|
from django.db.models.aggregates import Count
|
2012-09-09 07:51:36 +08:00
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2020-10-26 04:04:21 +08:00
|
|
|
from django.db.models.expressions import (
|
|
|
|
BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef,
|
|
|
|
)
|
2017-06-18 23:53:40 +08:00
|
|
|
from django.db.models.fields import Field
|
2015-02-02 19:48:30 +08:00
|
|
|
from django.db.models.fields.related_lookups import MultiColSource
|
2017-01-16 23:03:15 +08:00
|
|
|
from django.db.models.lookups import Lookup
|
2015-06-25 23:31:07 +08:00
|
|
|
from django.db.models.query_utils import (
|
2016-08-19 06:42:11 +08:00
|
|
|
Q, check_rel_lookup_compatibility, refs_expression,
|
2015-06-25 23:31:07 +08:00
|
|
|
)
|
2020-04-06 03:45:06 +08:00
|
|
|
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
|
2014-11-17 16:26:10 +08:00
|
|
|
from django.db.models.sql.datastructures import (
|
2017-09-03 21:20:51 +08:00
|
|
|
BaseTable, Empty, Join, MultiJoin,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
|
|
|
from django.db.models.sql.where import (
|
|
|
|
AND, OR, ExtraWhere, NothingNode, WhereNode,
|
|
|
|
)
|
2017-06-28 14:23:37 +08:00
|
|
|
from django.utils.functional import cached_property
|
2014-02-27 05:48:20 +08:00
|
|
|
from django.utils.tree import Node
|
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
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
__all__ = ['Query', 'RawQuery']
|
2009-12-20 10:46:58 +08:00
|
|
|
|
2012-09-07 22:58:17 +08:00
|
|
|
|
2015-01-07 08:16:35 +08:00
|
|
|
def get_field_names_from_opts(opts):
|
|
|
|
return set(chain.from_iterable(
|
|
|
|
(f.name, f.attname) if f.concrete else (f.name,)
|
|
|
|
for f in opts.get_fields()
|
|
|
|
))
|
|
|
|
|
|
|
|
|
2017-09-22 23:53:17 +08:00
|
|
|
def get_children_from_q(q):
|
|
|
|
for child in q.children:
|
|
|
|
if isinstance(child, Node):
|
|
|
|
yield from get_children_from_q(child)
|
|
|
|
else:
|
|
|
|
yield child
|
|
|
|
|
|
|
|
|
2017-08-01 22:37:02 +08:00
|
|
|
JoinInfo = namedtuple(
|
|
|
|
'JoinInfo',
|
2017-06-18 23:53:40 +08:00
|
|
|
('final_field', 'targets', 'opts', 'joins', 'path', 'transform_function')
|
2017-08-01 22:37:02 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class RawQuery:
|
2017-01-25 07:04:12 +08:00
|
|
|
"""A single raw SQL query."""
|
2009-12-20 10:46:58 +08:00
|
|
|
|
2020-11-29 00:08:27 +08:00
|
|
|
def __init__(self, sql, using, params=()):
|
|
|
|
self.params = params
|
2009-12-20 10:46:58 +08:00
|
|
|
self.sql = sql
|
2009-12-22 23:18:51 +08:00
|
|
|
self.using = using
|
2009-12-20 10:46:58 +08:00
|
|
|
self.cursor = None
|
|
|
|
|
2010-04-02 22:44:16 +08:00
|
|
|
# Mirror some properties of a normal query so that
|
|
|
|
# the compiler can be used to process results.
|
|
|
|
self.low_mark, self.high_mark = 0, None # Used for offset/limit
|
|
|
|
self.extra_select = {}
|
2013-12-25 21:13:18 +08:00
|
|
|
self.annotation_select = {}
|
2010-04-02 22:44:16 +08:00
|
|
|
|
2017-07-08 00:49:23 +08:00
|
|
|
def chain(self, using):
|
|
|
|
return self.clone(using)
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def clone(self, using):
|
2017-07-07 01:18:05 +08:00
|
|
|
return RawQuery(self.sql, using, params=self.params)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
def get_columns(self):
|
|
|
|
if self.cursor is None:
|
|
|
|
self._execute_query()
|
2018-11-21 16:06:50 +08:00
|
|
|
converter = connections[self.using].introspection.identifier_converter
|
2009-12-23 05:05:15 +08:00
|
|
|
return [converter(column_meta[0])
|
|
|
|
for column_meta in self.cursor.description]
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
# Always execute a new query for a new iterator.
|
2010-02-23 13:22:12 +08:00
|
|
|
# This could be optimized with a cache at the expense of RAM.
|
2009-12-20 10:46:58 +08:00
|
|
|
self._execute_query()
|
2010-04-15 21:01:51 +08:00
|
|
|
if not connections[self.using].features.can_use_chunked_reads:
|
|
|
|
# If the database can't use chunked reads we need to make sure we
|
|
|
|
# evaluate the entire query up front.
|
|
|
|
result = list(self.cursor)
|
|
|
|
else:
|
|
|
|
result = self.cursor
|
|
|
|
return iter(result)
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2016-12-01 21:08:51 +08:00
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self)
|
2014-08-17 22:21:48 +08:00
|
|
|
|
2015-05-02 21:54:17 +08:00
|
|
|
@property
|
|
|
|
def params_type(self):
|
2020-11-29 00:08:27 +08:00
|
|
|
if self.params is None:
|
|
|
|
return None
|
2015-05-02 21:54:17 +08:00
|
|
|
return dict if isinstance(self.params, Mapping) else tuple
|
|
|
|
|
2014-08-17 22:21:48 +08:00
|
|
|
def __str__(self):
|
2020-11-29 00:08:27 +08:00
|
|
|
if self.params_type is None:
|
|
|
|
return self.sql
|
2015-05-02 21:54:17 +08:00
|
|
|
return self.sql % self.params_type(self.params)
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
def _execute_query(self):
|
2015-05-02 21:54:17 +08:00
|
|
|
connection = connections[self.using]
|
|
|
|
|
|
|
|
# Adapt parameters to the database, as much as possible considering
|
|
|
|
# that the target type isn't known. See #17755.
|
|
|
|
params_type = self.params_type
|
2015-05-03 03:27:44 +08:00
|
|
|
adapter = connection.ops.adapt_unknown_value
|
2015-05-02 21:54:17 +08:00
|
|
|
if params_type is tuple:
|
|
|
|
params = tuple(adapter(val) for val in self.params)
|
|
|
|
elif params_type is dict:
|
2017-01-07 19:11:46 +08:00
|
|
|
params = {key: adapter(val) for key, val in self.params.items()}
|
2020-11-29 00:08:27 +08:00
|
|
|
elif params_type is None:
|
|
|
|
params = None
|
2015-05-02 21:54:17 +08:00
|
|
|
else:
|
|
|
|
raise RuntimeError("Unexpected params type: %s" % params_type)
|
|
|
|
|
|
|
|
self.cursor = connection.cursor()
|
|
|
|
self.cursor.execute(self.sql, 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
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2021-09-15 01:08:19 +08:00
|
|
|
ExplainInfo = namedtuple('ExplainInfo', ('format', 'options'))
|
|
|
|
|
|
|
|
|
2019-03-06 14:05:55 +08:00
|
|
|
class Query(BaseExpression):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""A single SQL query."""
|
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
|
|
|
|
|
|
|
alias_prefix = 'T'
|
2013-08-13 19:11:52 +08:00
|
|
|
subq_aliases = frozenset([alias_prefix])
|
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
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
compiler = 'SQLCompiler'
|
|
|
|
|
2021-07-21 03:38:17 +08:00
|
|
|
def __init__(self, model, alias_cols=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
|
|
|
self.model = model
|
2012-11-11 07:59:24 +08:00
|
|
|
self.alias_refcount = {}
|
2012-04-30 06:50:48 +08:00
|
|
|
# alias_map is the most important data structure regarding joins.
|
|
|
|
# It's used for recording which joins exist in the query and what
|
2014-11-17 16:26:10 +08:00
|
|
|
# types they are. The key is the alias of the joined table (possibly
|
|
|
|
# the table name) and the value is a Join-like object (see
|
|
|
|
# sql.datastructures.Join for more information).
|
2019-02-05 19:22:08 +08:00
|
|
|
self.alias_map = {}
|
2019-09-10 11:58:29 +08:00
|
|
|
# Whether to provide alias to columns during reference resolving.
|
|
|
|
self.alias_cols = alias_cols
|
2014-10-07 21:07:46 +08:00
|
|
|
# Sometimes the query contains references to aliases in outer queries (as
|
|
|
|
# a result of split_exclude). Correct alias quoting needs to know these
|
|
|
|
# aliases too.
|
2019-12-17 14:21:13 +08:00
|
|
|
# Map external tables to whether they are aliased.
|
|
|
|
self.external_aliases = {}
|
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
|
|
|
self.table_map = {} # Maps table names to list of aliases.
|
|
|
|
self.default_cols = True
|
|
|
|
self.default_ordering = True
|
|
|
|
self.standard_ordering = True
|
2008-08-23 06:00:28 +08:00
|
|
|
self.used_aliases = set()
|
|
|
|
self.filter_is_sticky = False
|
2016-10-28 23:20:23 +08:00
|
|
|
self.subquery = 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
|
|
|
|
2012-08-25 21:33:07 +08:00
|
|
|
# SQL-related attributes
|
2014-12-01 15:28:01 +08:00
|
|
|
# Select and related select clauses are expressions to use in the
|
|
|
|
# SELECT clause of the query.
|
2012-10-26 01:57:32 +08:00
|
|
|
# The select is used for cases where we want to set up the select
|
2014-12-01 15:28:01 +08:00
|
|
|
# clause to contain other than default fields (values(), subqueries...)
|
|
|
|
# Note that annotations go to annotations dictionary.
|
2017-03-08 22:25:44 +08:00
|
|
|
self.select = ()
|
2021-07-21 03:38:17 +08:00
|
|
|
self.where = WhereNode()
|
2014-12-01 15:28:01 +08:00
|
|
|
# The group_by attribute can have one of the following forms:
|
|
|
|
# - None: no group by at all in the query
|
2017-03-08 22:25:44 +08:00
|
|
|
# - A tuple of expressions: group by (at least) those expressions.
|
2014-12-01 15:28:01 +08:00
|
|
|
# String refs are also allowed for now.
|
|
|
|
# - True: group by all select fields of the model
|
|
|
|
# See compiler.get_group_by() for details.
|
2009-02-16 20:29:31 +08:00
|
|
|
self.group_by = None
|
2017-03-08 22:25:44 +08:00
|
|
|
self.order_by = ()
|
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
|
|
|
self.low_mark, self.high_mark = 0, None # Used for offset/limit
|
|
|
|
self.distinct = False
|
2017-03-08 22:25:44 +08:00
|
|
|
self.distinct_fields = ()
|
2011-04-21 04:42:07 +08:00
|
|
|
self.select_for_update = False
|
|
|
|
self.select_for_update_nowait = False
|
2016-06-23 23:52:14 +08:00
|
|
|
self.select_for_update_skip_locked = False
|
2017-06-30 04:00:15 +08:00
|
|
|
self.select_for_update_of = ()
|
2020-05-11 00:25:06 +08:00
|
|
|
self.select_for_no_key_update = False
|
2015-01-30 15:26:13 +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
|
|
|
self.select_related = False
|
2015-01-30 15:26:13 +08:00
|
|
|
# Arbitrary limit for select_related to prevents infinite recursion.
|
|
|
|
self.max_depth = 5
|
|
|
|
|
|
|
|
# Holds the selects defined by a call to values() or values_list()
|
|
|
|
# excluding annotation_select and extra_select.
|
2017-03-08 22:25:44 +08:00
|
|
|
self.values_select = ()
|
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
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
# SQL annotation-related attributes
|
2019-02-05 19:22:08 +08:00
|
|
|
self.annotations = {} # Maps alias -> Annotation Expression
|
2013-12-25 21:13:18 +08:00
|
|
|
self.annotation_select_mask = None
|
|
|
|
self._annotation_select_cache = None
|
2009-01-15 19:06:34 +08:00
|
|
|
|
2017-01-14 21:32:07 +08:00
|
|
|
# Set combination attributes
|
|
|
|
self.combinator = None
|
|
|
|
self.combinator_all = False
|
|
|
|
self.combined_queries = ()
|
|
|
|
|
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
|
|
|
# These are for extensions. The contents are more or less appended
|
|
|
|
# verbatim to the appropriate clause.
|
2019-02-05 19:22:08 +08:00
|
|
|
self.extra = {} # Maps col_alias -> (col_sql, params).
|
2009-04-30 23:40:09 +08:00
|
|
|
self.extra_select_mask = None
|
|
|
|
self._extra_select_cache = None
|
|
|
|
|
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
|
|
|
self.extra_tables = ()
|
|
|
|
self.extra_order_by = ()
|
|
|
|
|
2009-03-19 17:06:04 +08:00
|
|
|
# A tuple that is a set of model field names and either True, if these
|
|
|
|
# are the fields to defer, or False if these are the only fields to
|
|
|
|
# load.
|
2017-03-08 22:25:44 +08:00
|
|
|
self.deferred_loading = (frozenset(), True)
|
2009-03-19 17:06:04 +08:00
|
|
|
|
2017-09-22 23:53:17 +08:00
|
|
|
self._filtered_relations = {}
|
|
|
|
|
2021-09-15 01:08:19 +08:00
|
|
|
self.explain_info = None
|
2017-09-10 22:34:18 +08:00
|
|
|
|
2019-03-06 14:05:55 +08:00
|
|
|
@property
|
|
|
|
def output_field(self):
|
|
|
|
if len(self.select) == 1:
|
2020-04-05 02:55:20 +08:00
|
|
|
select = self.select[0]
|
|
|
|
return getattr(select, 'target', None) or select.field
|
2019-03-06 14:05:55 +08:00
|
|
|
elif len(self.annotation_select) == 1:
|
|
|
|
return next(iter(self.annotation_select.values())).output_field
|
|
|
|
|
2017-04-23 13:05:51 +08:00
|
|
|
@property
|
|
|
|
def has_select_fields(self):
|
|
|
|
return bool(self.select or self.annotation_select_mask or self.extra_select_mask)
|
|
|
|
|
2017-06-28 14:23:37 +08:00
|
|
|
@cached_property
|
|
|
|
def base_table(self):
|
2017-07-31 23:02:23 +08:00
|
|
|
for alias in self.alias_map:
|
|
|
|
return alias
|
2017-06-28 14:23:37 +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
|
|
|
def __str__(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the query as a string of SQL with the parameter values
|
2011-08-23 11:38:28 +08:00
|
|
|
substituted in (use sql_with_params() to see the unsubstituted string).
|
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
|
|
|
|
|
|
|
Parameter values won't necessarily be quoted correctly, since that is
|
|
|
|
done by the database interface at execution time.
|
|
|
|
"""
|
2011-08-23 11:38:28 +08:00
|
|
|
sql, params = self.sql_with_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
|
|
|
return sql % params
|
|
|
|
|
2011-08-23 11:38:28 +08:00
|
|
|
def sql_with_params(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the query as an SQL string and the parameters that will be
|
2014-04-27 01:18:45 +08:00
|
|
|
substituted into the query.
|
2011-08-23 11:38:28 +08:00
|
|
|
"""
|
|
|
|
return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
|
|
|
|
|
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 __deepcopy__(self, memo):
|
2017-07-07 21:29:58 +08:00
|
|
|
"""Limit the amount of work when a Query is deepcopied."""
|
|
|
|
result = self.clone()
|
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
|
|
|
memo[id(self)] = result
|
|
|
|
return result
|
|
|
|
|
2021-05-22 09:48:46 +08:00
|
|
|
def get_compiler(self, using=None, connection=None, elide_empty=True):
|
2009-12-22 23:18:51 +08:00
|
|
|
if using is None and connection is None:
|
|
|
|
raise ValueError("Need either using or connection")
|
|
|
|
if using:
|
|
|
|
connection = connections[using]
|
2021-05-22 09:48:46 +08:00
|
|
|
return connection.ops.compiler(self.compiler)(self, connection, using, elide_empty)
|
2008-04-28 22:14:41 +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
|
|
|
def get_meta(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the Options instance (the model._meta) from which to start
|
2008-12-08 10:39:51 +08:00
|
|
|
processing. Normally, this is self.model._meta, but it can be changed
|
|
|
|
by subclasses.
|
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
|
|
|
"""
|
|
|
|
return self.model._meta
|
|
|
|
|
2017-07-08 00:49:23 +08:00
|
|
|
def clone(self):
|
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-07-08 00:49:23 +08:00
|
|
|
Return a copy of the current Query. A lightweight alternative to
|
|
|
|
to deepcopy().
|
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 = Empty()
|
2017-07-08 00:49:23 +08:00
|
|
|
obj.__class__ = self.__class__
|
|
|
|
# Copy references to everything.
|
|
|
|
obj.__dict__ = self.__dict__.copy()
|
|
|
|
# Clone attributes that can't use shallow copy.
|
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.alias_refcount = self.alias_refcount.copy()
|
|
|
|
obj.alias_map = self.alias_map.copy()
|
2014-10-07 21:07:46 +08:00
|
|
|
obj.external_aliases = self.external_aliases.copy()
|
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.table_map = self.table_map.copy()
|
2012-06-02 09:13:36 +08:00
|
|
|
obj.where = self.where.clone()
|
2019-02-05 19:22:08 +08:00
|
|
|
obj.annotations = self.annotations.copy()
|
2021-09-17 13:08:55 +08:00
|
|
|
if self.annotation_select_mask is not None:
|
2013-12-25 21:13:18 +08:00
|
|
|
obj.annotation_select_mask = self.annotation_select_mask.copy()
|
2020-07-07 18:15:05 +08:00
|
|
|
obj.combined_queries = tuple(query.clone() for query in self.combined_queries)
|
2013-12-25 21:13:18 +08:00
|
|
|
# _annotation_select_cache cannot be copied, as doing so breaks the
|
|
|
|
# (necessary) state in which both annotations and
|
|
|
|
# _annotation_select_cache point to the same underlying objects.
|
2010-03-22 04:47:52 +08:00
|
|
|
# It will get re-populated in the cloned queryset the next time it's
|
|
|
|
# used.
|
2013-12-25 21:13:18 +08:00
|
|
|
obj._annotation_select_cache = None
|
2019-02-05 19:22:08 +08:00
|
|
|
obj.extra = self.extra.copy()
|
2021-09-17 13:08:55 +08:00
|
|
|
if self.extra_select_mask is not None:
|
2009-04-30 23:40:09 +08:00
|
|
|
obj.extra_select_mask = self.extra_select_mask.copy()
|
2021-09-17 13:08:55 +08:00
|
|
|
if self._extra_select_cache is not None:
|
2009-04-30 23:40:09 +08:00
|
|
|
obj._extra_select_cache = self._extra_select_cache.copy()
|
2019-09-24 03:51:43 +08:00
|
|
|
if self.select_related is not False:
|
|
|
|
# Use deepcopy because select_related stores fields in nested
|
|
|
|
# dicts.
|
|
|
|
obj.select_related = copy.deepcopy(obj.select_related)
|
2013-08-13 19:11:52 +08:00
|
|
|
if 'subq_aliases' in self.__dict__:
|
|
|
|
obj.subq_aliases = self.subq_aliases.copy()
|
2017-07-08 00:49:23 +08:00
|
|
|
obj.used_aliases = self.used_aliases.copy()
|
2017-09-22 23:53:17 +08:00
|
|
|
obj._filtered_relations = self._filtered_relations.copy()
|
2017-07-08 00:49:23 +08:00
|
|
|
# Clear the cached_property
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2017-07-08 00:49:23 +08:00
|
|
|
del obj.base_table
|
2017-09-07 20:16:21 +08:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
2017-07-08 00:49:23 +08:00
|
|
|
return obj
|
2011-12-23 04:42:40 +08:00
|
|
|
|
2017-07-08 00:49:23 +08:00
|
|
|
def chain(self, klass=None):
|
|
|
|
"""
|
|
|
|
Return a copy of the current Query that's ready for another operation.
|
|
|
|
The klass argument changes the type of the Query, e.g. UpdateQuery.
|
|
|
|
"""
|
|
|
|
obj = self.clone()
|
|
|
|
if klass and obj.__class__ != klass:
|
|
|
|
obj.__class__ = klass
|
|
|
|
if not obj.filter_is_sticky:
|
|
|
|
obj.used_aliases = set()
|
|
|
|
obj.filter_is_sticky = 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
|
|
|
if hasattr(obj, '_setup_query'):
|
|
|
|
obj._setup_query()
|
|
|
|
return obj
|
|
|
|
|
2014-10-07 21:07:46 +08:00
|
|
|
def relabeled_clone(self, change_map):
|
|
|
|
clone = self.clone()
|
|
|
|
clone.change_aliases(change_map)
|
|
|
|
return clone
|
|
|
|
|
2019-09-10 11:58:29 +08:00
|
|
|
def _get_col(self, target, field, alias):
|
|
|
|
if not self.alias_cols:
|
|
|
|
alias = None
|
|
|
|
return target.get_col(alias, field)
|
|
|
|
|
2014-11-20 20:30:25 +08:00
|
|
|
def rewrite_cols(self, annotation, col_cnt):
|
|
|
|
# We must make sure the inner query has the referred columns in it.
|
|
|
|
# If we are aggregating over an annotation, then Django uses Ref()
|
|
|
|
# instances to note this. However, if we are annotating over a column
|
|
|
|
# of a related model, then it might be that column isn't part of the
|
|
|
|
# SELECT clause of the inner query, and we must manually make sure
|
|
|
|
# the column is selected. An example case is:
|
|
|
|
# .aggregate(Sum('author__awards'))
|
|
|
|
# Resolving this expression results in a join to author, but there
|
|
|
|
# is no guarantee the awards column of author is in the select clause
|
|
|
|
# of the query. Thus we must manually add the column to the inner
|
|
|
|
# query.
|
|
|
|
orig_exprs = annotation.get_source_expressions()
|
|
|
|
new_exprs = []
|
|
|
|
for expr in orig_exprs:
|
2017-01-16 23:03:15 +08:00
|
|
|
# FIXME: These conditions are fairly arbitrary. Identify a better
|
|
|
|
# method of having expressions decide which code path they should
|
|
|
|
# take.
|
2014-11-20 20:30:25 +08:00
|
|
|
if isinstance(expr, Ref):
|
|
|
|
# Its already a Ref to subquery (see resolve_ref() for
|
|
|
|
# details)
|
|
|
|
new_exprs.append(expr)
|
2017-01-16 23:03:15 +08:00
|
|
|
elif isinstance(expr, (WhereNode, Lookup)):
|
|
|
|
# Decompose the subexpressions further. The code here is
|
|
|
|
# copied from the else clause, but this condition must appear
|
|
|
|
# before the contains_aggregate/is_summary condition below.
|
|
|
|
new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
|
|
|
|
new_exprs.append(new_expr)
|
2019-03-12 10:48:54 +08:00
|
|
|
else:
|
|
|
|
# Reuse aliases of expressions already selected in subquery.
|
2019-03-09 04:54:03 +08:00
|
|
|
for col_alias, selected_annotation in self.annotation_select.items():
|
2020-05-14 12:14:48 +08:00
|
|
|
if selected_annotation is expr:
|
2019-03-12 10:48:54 +08:00
|
|
|
new_expr = Ref(col_alias, expr)
|
2019-03-09 04:54:03 +08:00
|
|
|
break
|
|
|
|
else:
|
2019-03-12 10:48:54 +08:00
|
|
|
# An expression that is not selected the subquery.
|
|
|
|
if isinstance(expr, Col) or (expr.contains_aggregate and not expr.is_summary):
|
|
|
|
# Reference column or another aggregate. Select it
|
|
|
|
# under a non-conflicting alias.
|
|
|
|
col_cnt += 1
|
|
|
|
col_alias = '__col%d' % col_cnt
|
|
|
|
self.annotations[col_alias] = expr
|
|
|
|
self.append_annotation_mask([col_alias])
|
|
|
|
new_expr = Ref(col_alias, expr)
|
|
|
|
else:
|
|
|
|
# Some other expression not referencing database values
|
|
|
|
# directly. Its subexpression might contain Cols.
|
|
|
|
new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
|
2014-11-20 20:30:25 +08:00
|
|
|
new_exprs.append(new_expr)
|
|
|
|
annotation.set_source_expressions(new_exprs)
|
|
|
|
return annotation, col_cnt
|
|
|
|
|
2014-11-20 18:35:56 +08:00
|
|
|
def get_aggregation(self, using, added_aggregate_names):
|
2009-01-15 19:06:34 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the dictionary with the values of the existing aggregations.
|
2009-01-15 19:06:34 +08:00
|
|
|
"""
|
2013-12-25 21:13:18 +08:00
|
|
|
if not self.annotation_select:
|
2009-01-15 19:06:34 +08:00
|
|
|
return {}
|
2019-03-09 07:15:44 +08:00
|
|
|
existing_annotations = [
|
2013-12-25 21:13:18 +08:00
|
|
|
annotation for alias, annotation
|
2014-11-20 18:35:56 +08:00
|
|
|
in self.annotations.items()
|
|
|
|
if alias not in added_aggregate_names
|
2019-03-09 07:15:44 +08:00
|
|
|
]
|
2014-11-20 18:35:56 +08:00
|
|
|
# Decide if we need to use a subquery.
|
|
|
|
#
|
|
|
|
# Existing annotations would cause incorrect results as get_aggregation()
|
|
|
|
# must produce just one result and thus must not use GROUP BY. But we
|
|
|
|
# aren't smart enough to remove the existing annotations from the
|
|
|
|
# query, so those would force us to use GROUP BY.
|
|
|
|
#
|
2017-07-15 00:11:29 +08:00
|
|
|
# If the query has limit or distinct, or uses set operations, then
|
|
|
|
# those operations must be done in a subquery so that the query
|
|
|
|
# aggregates on the limit and/or distinct results instead of applying
|
|
|
|
# the distinct and limit after the aggregation.
|
2019-07-26 02:45:55 +08:00
|
|
|
if (isinstance(self.group_by, tuple) or self.is_sliced or existing_annotations or
|
2017-07-15 00:11:29 +08:00
|
|
|
self.distinct or self.combinator):
|
2010-11-17 10:57:14 +08:00
|
|
|
from django.db.models.sql.subqueries import AggregateQuery
|
2013-12-25 21:13:18 +08:00
|
|
|
inner_query = self.clone()
|
2020-11-04 05:50:10 +08:00
|
|
|
inner_query.subquery = True
|
|
|
|
outer_query = AggregateQuery(self.model, inner_query)
|
2013-12-25 21:13:18 +08:00
|
|
|
inner_query.select_for_update = False
|
|
|
|
inner_query.select_related = False
|
2019-03-09 07:15:44 +08:00
|
|
|
inner_query.set_annotation_mask(self.annotation_select)
|
2021-05-27 04:09:15 +08:00
|
|
|
# Queries with distinct_fields need ordering and when a limit is
|
|
|
|
# applied we must take the slice from the ordered query. Otherwise
|
|
|
|
# no need for ordering.
|
|
|
|
inner_query.clear_ordering(force=False)
|
2015-03-04 20:56:20 +08:00
|
|
|
if not inner_query.distinct:
|
|
|
|
# If the inner query uses default select and it has some
|
|
|
|
# aggregate annotations, then we must make sure the inner
|
|
|
|
# query is grouped by the main model's primary key. However,
|
|
|
|
# clearing the select clause can alter results if distinct is
|
|
|
|
# used.
|
2019-03-09 07:15:44 +08:00
|
|
|
has_existing_aggregate_annotations = any(
|
|
|
|
annotation for annotation in existing_annotations
|
|
|
|
if getattr(annotation, 'contains_aggregate', True)
|
|
|
|
)
|
|
|
|
if inner_query.default_cols and has_existing_aggregate_annotations:
|
2017-03-08 22:25:44 +08:00
|
|
|
inner_query.group_by = (self.model._meta.pk.get_col(inner_query.get_initial_alias()),)
|
2015-03-04 20:56:20 +08:00
|
|
|
inner_query.default_cols = False
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2017-06-28 14:23:37 +08:00
|
|
|
relabels = {t: 'subquery' for t in inner_query.alias_map}
|
2013-12-25 21:13:18 +08:00
|
|
|
relabels[None] = 'subquery'
|
2009-01-15 19:06:34 +08:00
|
|
|
# Remove any aggregates marked for reduction from the subquery
|
|
|
|
# and move them to the outer AggregateQuery.
|
2014-11-20 20:30:25 +08:00
|
|
|
col_cnt = 0
|
2015-01-20 09:54:57 +08:00
|
|
|
for alias, expression in list(inner_query.annotation_select.items()):
|
2019-03-09 07:15:44 +08:00
|
|
|
annotation_select_mask = inner_query.annotation_select_mask
|
2014-11-20 20:30:25 +08:00
|
|
|
if expression.is_summary:
|
|
|
|
expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt)
|
|
|
|
outer_query.annotations[alias] = expression.relabeled_clone(relabels)
|
2015-03-04 20:56:20 +08:00
|
|
|
del inner_query.annotations[alias]
|
2019-03-09 07:15:44 +08:00
|
|
|
annotation_select_mask.remove(alias)
|
2015-03-04 20:56:20 +08:00
|
|
|
# Make sure the annotation_select wont use cached results.
|
|
|
|
inner_query.set_annotation_mask(inner_query.annotation_select_mask)
|
2017-03-08 22:25:44 +08:00
|
|
|
if inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask:
|
2015-03-04 20:56:20 +08:00
|
|
|
# In case of Model.objects[0:3].count(), there would be no
|
|
|
|
# field selected in the inner query, yet we must use a subquery.
|
|
|
|
# So, make sure at least one field is selected.
|
2017-03-08 22:25:44 +08:00
|
|
|
inner_query.select = (self.model._meta.pk.get_col(inner_query.get_initial_alias()),)
|
2009-01-15 19:06:34 +08:00
|
|
|
else:
|
2013-12-25 21:13:18 +08:00
|
|
|
outer_query = self
|
2017-03-08 22:25:44 +08:00
|
|
|
self.select = ()
|
2009-01-15 19:06:34 +08:00
|
|
|
self.default_cols = False
|
2019-02-05 19:22:08 +08:00
|
|
|
self.extra = {}
|
2009-01-15 19:06:34 +08:00
|
|
|
|
2021-05-22 10:32:16 +08:00
|
|
|
empty_aggregate_result = [
|
|
|
|
expression.empty_aggregate_value
|
|
|
|
for expression in outer_query.annotation_select.values()
|
|
|
|
]
|
|
|
|
elide_empty = not any(result is NotImplemented for result in empty_aggregate_result)
|
2021-05-27 04:09:15 +08:00
|
|
|
outer_query.clear_ordering(force=True)
|
2013-12-25 21:13:18 +08:00
|
|
|
outer_query.clear_limits()
|
|
|
|
outer_query.select_for_update = False
|
|
|
|
outer_query.select_related = False
|
2021-05-22 10:32:16 +08:00
|
|
|
compiler = outer_query.get_compiler(using, elide_empty=elide_empty)
|
2013-12-25 21:13:18 +08:00
|
|
|
result = compiler.execute_sql(SINGLE)
|
2021-05-22 10:32:16 +08:00
|
|
|
if result is None:
|
|
|
|
result = empty_aggregate_result
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
converters = compiler.get_converters(outer_query.annotation_select.values())
|
2017-08-08 05:06:15 +08:00
|
|
|
result = next(compiler.apply_converters((result,), converters))
|
2009-01-23 19:03:48 +08:00
|
|
|
|
2017-08-15 21:59:31 +08:00
|
|
|
return dict(zip(outer_query.annotation_select, result))
|
2009-01-15 19:06:34 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_count(self, using):
|
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-01-25 07:04:12 +08:00
|
|
|
Perform a COUNT() query using the current filter constraints.
|
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 = self.clone()
|
2014-11-20 18:35:56 +08:00
|
|
|
obj.add_annotation(Count('*'), alias='__count', is_summary=True)
|
|
|
|
number = obj.get_aggregation(using, ['__count'])['__count']
|
|
|
|
if number is None:
|
|
|
|
number = 0
|
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
|
|
|
return number
|
|
|
|
|
2013-10-09 20:29:14 +08:00
|
|
|
def has_filters(self):
|
2014-12-23 21:16:56 +08:00
|
|
|
return self.where
|
2013-10-09 20:29:14 +08:00
|
|
|
|
2020-11-12 06:16:32 +08:00
|
|
|
def exists(self, using, limit=True):
|
2009-10-24 08:28:39 +08:00
|
|
|
q = self.clone()
|
2013-10-06 02:40:36 +08:00
|
|
|
if not q.distinct:
|
2015-05-25 01:05:56 +08:00
|
|
|
if q.group_by is True:
|
|
|
|
q.add_fields((f.attname for f in self.model._meta.concrete_fields), False)
|
2019-12-22 12:22:49 +08:00
|
|
|
# Disable GROUP BY aliases to avoid orphaning references to the
|
|
|
|
# SELECT clause which is about to be cleared.
|
|
|
|
q.set_group_by(allow_aliases=False)
|
2013-10-06 02:40:36 +08:00
|
|
|
q.clear_select_clause()
|
2020-11-12 06:16:32 +08:00
|
|
|
if q.combined_queries and q.combinator == 'union':
|
|
|
|
limit_combined = connections[using].features.supports_slicing_ordering_in_compound
|
|
|
|
q.combined_queries = tuple(
|
|
|
|
combined_query.exists(using, limit=limit_combined)
|
|
|
|
for combined_query in q.combined_queries
|
|
|
|
)
|
2021-05-27 04:09:15 +08:00
|
|
|
q.clear_ordering(force=True)
|
2020-11-12 06:16:32 +08:00
|
|
|
if limit:
|
|
|
|
q.set_limits(high=1)
|
2020-08-13 11:16:22 +08:00
|
|
|
q.add_extra({'a': 1}, None, None, None, None, None)
|
|
|
|
q.set_extra_mask(['a'])
|
|
|
|
return q
|
|
|
|
|
|
|
|
def has_results(self, using):
|
2020-11-12 06:16:32 +08:00
|
|
|
q = self.exists(using)
|
2009-12-22 23:18:51 +08:00
|
|
|
compiler = q.get_compiler(using=using)
|
2013-07-08 23:05:08 +08:00
|
|
|
return compiler.has_results()
|
2009-01-05 19:47:48 +08:00
|
|
|
|
2017-09-10 22:34:18 +08:00
|
|
|
def explain(self, using, format=None, **options):
|
|
|
|
q = self.clone()
|
2021-09-15 01:08:19 +08:00
|
|
|
q.explain_info = ExplainInfo(format, options)
|
2017-09-10 22:34:18 +08:00
|
|
|
compiler = q.get_compiler(using=using)
|
|
|
|
return '\n'.join(compiler.explain_query())
|
|
|
|
|
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, rhs, connector):
|
|
|
|
"""
|
|
|
|
Merge the 'rhs' query into the current one (with any 'rhs' effects
|
|
|
|
being applied *after* (that is, "to the right of") anything in the
|
|
|
|
current query. 'rhs' is not modified during a call to this function.
|
|
|
|
|
|
|
|
The 'connector' parameter describes how to connect filters from the
|
|
|
|
'rhs' query.
|
|
|
|
"""
|
2021-03-24 13:45:08 +08:00
|
|
|
if self.model != rhs.model:
|
|
|
|
raise TypeError('Cannot combine queries on two different base models.')
|
2021-03-10 16:16:28 +08:00
|
|
|
if self.is_sliced:
|
|
|
|
raise TypeError('Cannot combine queries once a slice has been taken.')
|
2021-03-24 13:45:08 +08:00
|
|
|
if self.distinct != rhs.distinct:
|
|
|
|
raise TypeError('Cannot combine a unique query with a non-unique query.')
|
|
|
|
if self.distinct_fields != rhs.distinct_fields:
|
|
|
|
raise TypeError('Cannot combine queries with different distinct fields.')
|
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
|
|
|
|
|
|
|
# Work out how to relabel the rhs aliases, if necessary.
|
|
|
|
change_map = {}
|
|
|
|
conjunction = (connector == AND)
|
2012-08-11 03:00:21 +08:00
|
|
|
|
|
|
|
# Determine which existing joins can be reused. When combining the
|
|
|
|
# query with AND we must recreate all joins for m2m filters. When
|
|
|
|
# combining with OR we can reuse joins. The reason is that in AND
|
|
|
|
# case a single row can't fulfill a condition like:
|
|
|
|
# revrel__col=1 & revrel__col=2
|
|
|
|
# But, there might be two different related rows matching this
|
|
|
|
# condition. In OR case a single True is enough, so single row is
|
|
|
|
# enough, too.
|
|
|
|
#
|
|
|
|
# Note that we will be creating duplicate joins for non-m2m joins in
|
|
|
|
# the AND case. The results will be correct but this creates too many
|
|
|
|
# joins. This is something that could be fixed later on.
|
2017-06-28 14:23:37 +08:00
|
|
|
reuse = set() if conjunction else set(self.alias_map)
|
2012-08-11 03:00:21 +08:00
|
|
|
# Base table must be present in the query - this is the same
|
|
|
|
# table on both sides.
|
|
|
|
self.get_initial_alias()
|
2014-01-09 01:35:47 +08:00
|
|
|
joinpromoter = JoinPromoter(connector, 2, False)
|
2013-11-05 00:04:57 +08:00
|
|
|
joinpromoter.add_votes(
|
2014-11-17 16:26:10 +08:00
|
|
|
j for j in self.alias_map if self.alias_map[j].join_type == INNER)
|
2013-11-05 00:04:57 +08:00
|
|
|
rhs_votes = set()
|
2012-08-11 03:00:21 +08:00
|
|
|
# Now, add the joins from rhs query into the new query (skipping base
|
|
|
|
# table).
|
2017-06-28 14:23:37 +08:00
|
|
|
rhs_tables = list(rhs.alias_map)[1:]
|
|
|
|
for alias in rhs_tables:
|
2014-11-17 16:26:10 +08:00
|
|
|
join = rhs.alias_map[alias]
|
2011-05-06 04:26:26 +08:00
|
|
|
# If the left side of the join was already relabeled, use the
|
|
|
|
# updated alias.
|
2014-11-17 16:26:10 +08:00
|
|
|
join = join.relabeled_clone(change_map)
|
|
|
|
new_alias = self.join(join, reuse=reuse)
|
|
|
|
if join.join_type == INNER:
|
2013-11-05 00:04:57 +08:00
|
|
|
rhs_votes.add(new_alias)
|
2012-08-11 03:00:21 +08:00
|
|
|
# We can't reuse the same join again in the query. If we have two
|
|
|
|
# distinct joins for the same connection in rhs query, then the
|
|
|
|
# combined query must have two joins, too.
|
|
|
|
reuse.discard(new_alias)
|
2015-08-21 00:46:14 +08:00
|
|
|
if alias != new_alias:
|
|
|
|
change_map[alias] = new_alias
|
2012-08-25 21:33:07 +08:00
|
|
|
if not rhs.alias_refcount[alias]:
|
|
|
|
# The alias was unused in the rhs query. Unref it so that it
|
|
|
|
# will be unused in the new query, too. We have to add and
|
|
|
|
# unref the alias so that join promotion has information of
|
|
|
|
# the join type for the unused alias.
|
|
|
|
self.unref_alias(new_alias)
|
2013-11-05 00:04:57 +08:00
|
|
|
joinpromoter.add_votes(rhs_votes)
|
|
|
|
joinpromoter.update_join_types(self)
|
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
|
|
|
|
2021-04-21 10:25:52 +08:00
|
|
|
# Combine subqueries aliases to ensure aliases relabelling properly
|
|
|
|
# handle subqueries when combining where and select clauses.
|
|
|
|
self.subq_aliases |= rhs.subq_aliases
|
|
|
|
|
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
|
|
|
# Now relabel a copy of the rhs where-clause and add it to the current
|
|
|
|
# one.
|
2015-02-04 16:21:29 +08:00
|
|
|
w = rhs.where.clone()
|
|
|
|
w.relabel_aliases(change_map)
|
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
|
|
|
self.where.add(w, connector)
|
|
|
|
|
|
|
|
# Selection columns and extra extensions are those provided by 'rhs'.
|
2017-03-08 22:25:44 +08:00
|
|
|
if rhs.select:
|
|
|
|
self.set_select([col.relabeled_clone(change_map) for col in rhs.select])
|
|
|
|
else:
|
|
|
|
self.select = ()
|
2008-06-30 14:24:21 +08:00
|
|
|
|
|
|
|
if connector == OR:
|
|
|
|
# It would be nice to be able to handle this, but the queries don't
|
|
|
|
# really make sense (or return consistent value sets). Not worth
|
|
|
|
# the extra complexity when you can write a real query instead.
|
2019-02-05 19:22:08 +08:00
|
|
|
if self.extra and rhs.extra:
|
2019-02-14 02:59:44 +08:00
|
|
|
raise ValueError("When merging querysets using 'or', you cannot have extra(select=...) on both sides.")
|
2009-04-30 23:40:09 +08:00
|
|
|
self.extra.update(rhs.extra)
|
|
|
|
extra_select_mask = set()
|
|
|
|
if self.extra_select_mask is not None:
|
|
|
|
extra_select_mask.update(self.extra_select_mask)
|
|
|
|
if rhs.extra_select_mask is not None:
|
|
|
|
extra_select_mask.update(rhs.extra_select_mask)
|
|
|
|
if extra_select_mask:
|
|
|
|
self.set_extra_mask(extra_select_mask)
|
2008-06-30 14:24:21 +08:00
|
|
|
self.extra_tables += rhs.extra_tables
|
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
|
|
|
|
|
|
|
# Ordering uses the 'rhs' ordering, unless it has none, in which case
|
|
|
|
# the current ordering is used.
|
2017-11-06 23:23:29 +08:00
|
|
|
self.order_by = rhs.order_by or self.order_by
|
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
|
|
|
self.extra_order_by = rhs.extra_order_by or self.extra_order_by
|
|
|
|
|
2009-03-19 17:06:04 +08:00
|
|
|
def deferred_to_data(self, target, callback):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Convert the self.deferred_loading data structure to an alternate data
|
2009-03-19 17:06:04 +08:00
|
|
|
structure, describing the field that *will* be loaded. This is used to
|
|
|
|
compute the columns to select from the database and also by the
|
2014-03-02 22:25:53 +08:00
|
|
|
QuerySet class to work out which fields are being initialized on each
|
2009-03-19 17:06:04 +08:00
|
|
|
model. Models that have all their fields included aren't mentioned in
|
|
|
|
the result, only those that have field restrictions in place.
|
|
|
|
|
|
|
|
The "target" parameter is the instance that is populated (in place).
|
|
|
|
The "callback" is a function that is called whenever a (model, field)
|
|
|
|
pair need to be added to "target". It accepts three parameters:
|
|
|
|
"target", and the model and list of fields being added for that model.
|
|
|
|
"""
|
|
|
|
field_names, defer = self.deferred_loading
|
|
|
|
if not field_names:
|
|
|
|
return
|
2013-05-14 03:40:39 +08:00
|
|
|
orig_opts = self.get_meta()
|
2009-03-19 17:06:04 +08:00
|
|
|
seen = {}
|
2014-09-26 20:31:50 +08:00
|
|
|
must_include = {orig_opts.concrete_model: {orig_opts.pk}}
|
2009-03-19 17:06:04 +08:00
|
|
|
for field_name in field_names:
|
|
|
|
parts = field_name.split(LOOKUP_SEP)
|
2014-02-15 19:24:20 +08:00
|
|
|
cur_model = self.model._meta.concrete_model
|
2009-04-04 13:35:01 +08:00
|
|
|
opts = orig_opts
|
2009-03-19 17:06:04 +08:00
|
|
|
for name in parts[:-1]:
|
|
|
|
old_model = cur_model
|
2017-09-22 23:53:17 +08:00
|
|
|
if name in self._filtered_relations:
|
|
|
|
name = self._filtered_relations[name].relation_name
|
2015-01-07 08:16:35 +08:00
|
|
|
source = opts.get_field(name)
|
2012-11-29 00:16:00 +08:00
|
|
|
if is_reverse_o2o(source):
|
2015-01-07 08:16:35 +08:00
|
|
|
cur_model = source.related_model
|
2012-11-29 00:16:00 +08:00
|
|
|
else:
|
2015-02-26 22:19:17 +08:00
|
|
|
cur_model = source.remote_field.model
|
2009-03-19 17:06:04 +08:00
|
|
|
opts = cur_model._meta
|
|
|
|
# Even if we're "just passing through" this model, we must add
|
|
|
|
# both the current model's pk and the related reference field
|
2012-11-29 00:16:00 +08:00
|
|
|
# (if it's not a reverse relation) to the things we select.
|
|
|
|
if not is_reverse_o2o(source):
|
|
|
|
must_include[old_model].add(source)
|
2009-03-19 17:06:04 +08:00
|
|
|
add_to_dict(must_include, cur_model, opts.pk)
|
2015-01-07 08:16:35 +08:00
|
|
|
field = opts.get_field(parts[-1])
|
|
|
|
is_reverse_object = field.auto_created and not field.concrete
|
|
|
|
model = field.related_model if is_reverse_object else field.model
|
|
|
|
model = model._meta.concrete_model
|
|
|
|
if model == opts.model:
|
2009-03-19 17:06:04 +08:00
|
|
|
model = cur_model
|
2012-11-29 00:16:00 +08:00
|
|
|
if not is_reverse_o2o(field):
|
|
|
|
add_to_dict(seen, model, field)
|
2009-03-19 17:06:04 +08:00
|
|
|
|
|
|
|
if defer:
|
|
|
|
# We need to load all fields for each model, except those that
|
|
|
|
# appear in "seen" (for all models that appear in "seen"). The only
|
|
|
|
# slight complexity here is handling fields that exist on parent
|
|
|
|
# models.
|
|
|
|
workset = {}
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, values in seen.items():
|
2017-08-31 08:59:45 +08:00
|
|
|
for field in model._meta.local_fields:
|
2018-01-12 22:05:16 +08:00
|
|
|
if field not in values:
|
|
|
|
m = field.model._meta.concrete_model
|
|
|
|
add_to_dict(workset, m, field)
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, values in must_include.items():
|
2009-03-19 17:06:04 +08:00
|
|
|
# If we haven't included a model in workset, we don't add the
|
|
|
|
# corresponding must_include fields for that model, since an
|
|
|
|
# empty set means "include all fields". That's why there's no
|
|
|
|
# "else" branch here.
|
|
|
|
if model in workset:
|
|
|
|
workset[model].update(values)
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, values in workset.items():
|
2009-03-19 17:06:04 +08:00
|
|
|
callback(target, model, values)
|
|
|
|
else:
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, values in must_include.items():
|
2009-03-19 17:06:04 +08:00
|
|
|
if model in seen:
|
|
|
|
seen[model].update(values)
|
|
|
|
else:
|
|
|
|
# As we've passed through this model, but not explicitly
|
|
|
|
# included any fields, we have to make sure it's mentioned
|
|
|
|
# so that only the "must include" fields are pulled in.
|
|
|
|
seen[model] = values
|
2009-06-06 14:14:05 +08:00
|
|
|
# Now ensure that every model in the inheritance chain is mentioned
|
|
|
|
# in the parent list. Again, it must be mentioned to ensure that
|
|
|
|
# only "must include" fields are pulled in.
|
|
|
|
for model in orig_opts.get_parent_list():
|
2017-11-14 05:15:49 +08:00
|
|
|
seen.setdefault(model, set())
|
2017-01-07 19:11:46 +08:00
|
|
|
for model, values in seen.items():
|
2009-03-19 17:06:04 +08:00
|
|
|
callback(target, model, values)
|
|
|
|
|
2017-09-22 23:53:17 +08:00
|
|
|
def table_alias(self, table_name, create=False, filtered_relation=None):
|
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-01-25 07:04:12 +08:00
|
|
|
Return a table alias for the given table_name and whether this is a
|
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
|
|
|
new alias or not.
|
|
|
|
|
|
|
|
If 'create' is true, a new alias is always created. Otherwise, the
|
|
|
|
most recently created alias for the table (if one exists) is reused.
|
|
|
|
"""
|
2014-06-14 18:50:18 +08:00
|
|
|
alias_list = self.table_map.get(table_name)
|
|
|
|
if not create and alias_list:
|
|
|
|
alias = alias_list[0]
|
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
|
|
|
self.alias_refcount[alias] += 1
|
|
|
|
return alias, False
|
|
|
|
|
|
|
|
# Create a new alias for this table.
|
2014-06-14 18:50:18 +08:00
|
|
|
if alias_list:
|
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
|
|
|
alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)
|
2014-06-14 18:50:18 +08:00
|
|
|
alias_list.append(alias)
|
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
|
|
|
else:
|
2014-04-27 01:18:45 +08:00
|
|
|
# The first occurrence of a table uses the table name directly.
|
2017-09-22 23:53:17 +08:00
|
|
|
alias = filtered_relation.alias if filtered_relation is not None else table_name
|
|
|
|
self.table_map[table_name] = [alias]
|
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
|
|
|
self.alias_refcount[alias] = 1
|
|
|
|
return alias, True
|
|
|
|
|
|
|
|
def ref_alias(self, alias):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Increases the reference count for this alias."""
|
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
|
|
|
self.alias_refcount[alias] += 1
|
|
|
|
|
2011-12-23 04:42:40 +08:00
|
|
|
def unref_alias(self, alias, amount=1):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Decreases the reference count for this alias."""
|
2011-12-23 04:42:40 +08:00
|
|
|
self.alias_refcount[alias] -= amount
|
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
|
|
|
|
2013-08-07 17:38:30 +08:00
|
|
|
def promote_joins(self, aliases):
|
2012-08-22 02:54:14 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Promote recursively the join type of given aliases and its children to
|
|
|
|
an outer join. If 'unconditional' is False, only promote the join if
|
2012-08-22 02:54:14 +08:00
|
|
|
it is nullable or the parent join is an outer join.
|
|
|
|
|
2013-11-05 00:04:57 +08:00
|
|
|
The children promotion is done to avoid join chains that contain a LOUTER
|
|
|
|
b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
|
|
|
|
then we must also promote b->c automatically, or otherwise the promotion
|
|
|
|
of a->b doesn't actually change anything in the query results.
|
2012-08-22 02:54:14 +08:00
|
|
|
"""
|
|
|
|
aliases = list(aliases)
|
|
|
|
while aliases:
|
|
|
|
alias = aliases.pop(0)
|
2014-11-17 16:26:10 +08:00
|
|
|
if self.alias_map[alias].join_type is None:
|
2012-10-08 23:36:51 +08:00
|
|
|
# This is the base table (first FROM entry) - this table
|
|
|
|
# isn't really joined at all in the query, so we should not
|
|
|
|
# alter its join type.
|
|
|
|
continue
|
2013-08-07 17:38:30 +08:00
|
|
|
# Only the first alias (skipped above) should have None join_type
|
|
|
|
assert self.alias_map[alias].join_type is not None
|
2014-11-17 16:26:10 +08:00
|
|
|
parent_alias = self.alias_map[alias].parent_alias
|
2016-04-04 08:37:32 +08:00
|
|
|
parent_louter = parent_alias and self.alias_map[parent_alias].join_type == LOUTER
|
2014-11-17 16:26:10 +08:00
|
|
|
already_louter = self.alias_map[alias].join_type == LOUTER
|
2013-08-07 17:38:30 +08:00
|
|
|
if ((self.alias_map[alias].nullable or parent_louter) and
|
|
|
|
not already_louter):
|
2014-11-17 16:26:10 +08:00
|
|
|
self.alias_map[alias] = self.alias_map[alias].promote()
|
2012-08-22 02:54:14 +08:00
|
|
|
# Join type of 'alias' changed, so re-examine all aliases that
|
|
|
|
# refer to this one.
|
|
|
|
aliases.extend(
|
2017-05-28 07:08:46 +08:00
|
|
|
join for join in self.alias_map
|
2016-04-04 08:37:32 +08:00
|
|
|
if self.alias_map[join].parent_alias == alias and join not in aliases
|
|
|
|
)
|
2008-09-02 21:52:07 +08:00
|
|
|
|
2013-11-05 00:04:57 +08:00
|
|
|
def demote_joins(self, aliases):
|
|
|
|
"""
|
|
|
|
Change join type from LOUTER to INNER for all joins in aliases.
|
|
|
|
|
|
|
|
Similarly to promote_joins(), this method must ensure no join chains
|
|
|
|
containing first an outer, then an inner join are generated. If we
|
|
|
|
are demoting b->c join in chain a LOUTER b LOUTER c then we must
|
|
|
|
demote a->b automatically, or otherwise the demotion of b->c doesn't
|
|
|
|
actually change anything in the query results. .
|
|
|
|
"""
|
|
|
|
aliases = list(aliases)
|
|
|
|
while aliases:
|
|
|
|
alias = aliases.pop(0)
|
2014-11-17 16:26:10 +08:00
|
|
|
if self.alias_map[alias].join_type == LOUTER:
|
|
|
|
self.alias_map[alias] = self.alias_map[alias].demote()
|
|
|
|
parent_alias = self.alias_map[alias].parent_alias
|
|
|
|
if self.alias_map[parent_alias].join_type == INNER:
|
2013-11-05 00:04:57 +08:00
|
|
|
aliases.append(parent_alias)
|
|
|
|
|
2011-12-23 04:42:40 +08:00
|
|
|
def reset_refcounts(self, to_counts):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Reset reference counts for aliases so that they match the value passed
|
|
|
|
in `to_counts`.
|
2011-12-23 04:42:40 +08:00
|
|
|
"""
|
|
|
|
for alias, cur_refcount in self.alias_refcount.copy().items():
|
|
|
|
unref_amount = cur_refcount - to_counts.get(alias, 0)
|
|
|
|
self.unref_alias(alias, unref_amount)
|
|
|
|
|
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 change_aliases(self, change_map):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Change the aliases in change_map (which maps old-alias -> new-alias),
|
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
|
|
|
relabelling any references to them in select columns and the where
|
|
|
|
clause.
|
|
|
|
"""
|
2017-07-29 22:16:43 +08:00
|
|
|
assert set(change_map).isdisjoint(change_map.values())
|
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
|
|
|
|
2009-02-23 22:47:59 +08:00
|
|
|
# 1. Update references in "select" (normal columns plus aliases),
|
2014-12-23 21:16:56 +08:00
|
|
|
# "group by" and "where".
|
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
|
|
|
self.where.relabel_aliases(change_map)
|
2017-03-08 22:25:44 +08:00
|
|
|
if isinstance(self.group_by, tuple):
|
|
|
|
self.group_by = tuple([col.relabeled_clone(change_map) for col in self.group_by])
|
|
|
|
self.select = tuple([col.relabeled_clone(change_map) for col in self.select])
|
2019-02-05 19:22:08 +08:00
|
|
|
self.annotations = self.annotations and {
|
|
|
|
key: col.relabeled_clone(change_map) for key, col in self.annotations.items()
|
|
|
|
}
|
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
|
|
|
|
|
|
|
# 2. Rename the alias in the internal table/alias datastructures.
|
2017-01-07 19:11:46 +08:00
|
|
|
for old_alias, new_alias in change_map.items():
|
2014-11-17 16:26:10 +08:00
|
|
|
if old_alias not in self.alias_map:
|
2014-10-07 21:07:46 +08:00
|
|
|
continue
|
2014-11-17 16:26:10 +08:00
|
|
|
alias_data = self.alias_map[old_alias].relabeled_clone(change_map)
|
|
|
|
self.alias_map[new_alias] = alias_data
|
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
|
|
|
self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
|
|
|
|
del self.alias_refcount[old_alias]
|
|
|
|
del self.alias_map[old_alias]
|
|
|
|
|
2012-04-30 06:50:48 +08:00
|
|
|
table_aliases = self.table_map[alias_data.table_name]
|
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
|
|
|
for pos, alias in enumerate(table_aliases):
|
|
|
|
if alias == old_alias:
|
|
|
|
table_aliases[pos] = new_alias
|
|
|
|
break
|
2019-12-17 14:21:13 +08:00
|
|
|
self.external_aliases = {
|
|
|
|
# Table is aliased or it's being changed and thus is aliased.
|
|
|
|
change_map.get(alias, alias): (aliased or alias in change_map)
|
|
|
|
for alias, aliased in self.external_aliases.items()
|
|
|
|
}
|
2014-10-07 21:07:46 +08:00
|
|
|
|
2013-08-13 19:11:52 +08:00
|
|
|
def bump_prefix(self, outer_query):
|
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-01-25 07:04:12 +08:00
|
|
|
Change the alias prefix to the next letter in the alphabet in a way
|
2013-08-13 19:11:52 +08:00
|
|
|
that the outer query's aliases and this query's aliases will not
|
|
|
|
conflict. Even tables that previously had no alias will get an alias
|
|
|
|
after this call.
|
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-15 21:45:00 +08:00
|
|
|
def prefix_gen():
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Generate a sequence of characters in alphabetical order:
|
2014-11-15 21:45:00 +08:00
|
|
|
-> 'A', 'B', 'C', ...
|
|
|
|
|
|
|
|
When the alphabet is finished, the sequence will continue with the
|
|
|
|
Cartesian product:
|
|
|
|
-> 'AA', 'AB', 'AC', ...
|
|
|
|
"""
|
|
|
|
alphabet = ascii_uppercase
|
|
|
|
prefix = chr(ord(self.alias_prefix) + 1)
|
|
|
|
yield prefix
|
|
|
|
for n in count(1):
|
|
|
|
seq = alphabet[alphabet.index(prefix):] if prefix else alphabet
|
|
|
|
for s in product(seq, repeat=n):
|
|
|
|
yield ''.join(s)
|
|
|
|
prefix = None
|
|
|
|
|
2013-11-03 04:35:45 +08:00
|
|
|
if self.alias_prefix != outer_query.alias_prefix:
|
|
|
|
# No clashes between self and outer query should be possible.
|
|
|
|
return
|
2014-11-15 21:45:00 +08:00
|
|
|
|
2019-04-05 12:37:58 +08:00
|
|
|
# Explicitly avoid infinite loop. The constant divider is based on how
|
|
|
|
# much depth recursive subquery references add to the stack. This value
|
|
|
|
# might need to be adjusted when adding or removing function calls from
|
|
|
|
# the code path in charge of performing these operations.
|
|
|
|
local_recursion_limit = sys.getrecursionlimit() // 16
|
2014-11-15 21:45:00 +08:00
|
|
|
for pos, prefix in enumerate(prefix_gen()):
|
|
|
|
if prefix not in self.subq_aliases:
|
|
|
|
self.alias_prefix = prefix
|
|
|
|
break
|
|
|
|
if pos > local_recursion_limit:
|
2019-04-05 12:40:54 +08:00
|
|
|
raise RecursionError(
|
2014-11-15 21:45:00 +08:00
|
|
|
'Maximum recursion depth exceeded: too many subqueries.'
|
|
|
|
)
|
2013-08-13 19:11:52 +08:00
|
|
|
self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
|
|
|
|
outer_query.subq_aliases = outer_query.subq_aliases.union(self.subq_aliases)
|
2019-02-05 19:22:08 +08:00
|
|
|
self.change_aliases({
|
|
|
|
alias: '%s%d' % (self.alias_prefix, pos)
|
|
|
|
for pos, alias in enumerate(self.alias_map)
|
|
|
|
})
|
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 get_initial_alias(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the first alias for this query, after increasing its reference
|
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
|
|
|
count.
|
|
|
|
"""
|
2017-06-28 14:23:37 +08:00
|
|
|
if self.alias_map:
|
|
|
|
alias = self.base_table
|
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
|
|
|
self.ref_alias(alias)
|
|
|
|
else:
|
2014-11-17 16:26:10 +08:00
|
|
|
alias = self.join(BaseTable(self.get_meta().db_table, None))
|
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
|
|
|
return alias
|
|
|
|
|
|
|
|
def count_active_tables(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the number of tables in this query with a non-zero reference
|
|
|
|
count. After execution, the reference counts are zeroed, so tables
|
|
|
|
added in compiler will not be seen by this method.
|
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
|
|
|
"""
|
2012-11-11 07:59:24 +08:00
|
|
|
return len([1 for count in self.alias_refcount.values() if count])
|
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
|
|
|
|
2021-02-08 20:02:58 +08:00
|
|
|
def join(self, join, reuse=None):
|
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-06-14 02:16:52 +08:00
|
|
|
Return an alias for the 'join', either reusing an existing alias for
|
|
|
|
that join or creating a new one. 'join' is either a
|
|
|
|
sql.datastructures.BaseTable or Join.
|
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-06-14 02:16:52 +08:00
|
|
|
The 'reuse' parameter can be either None which means all joins are
|
|
|
|
reusable, or it can be a set containing the aliases that can be reused.
|
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
|
|
|
|
2012-08-22 02:54:14 +08:00
|
|
|
A join is always created as LOUTER if the lhs alias is LOUTER to make
|
2017-06-14 02:16:52 +08:00
|
|
|
sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new
|
|
|
|
joins are created as LOUTER if the join is nullable.
|
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
|
|
|
"""
|
2021-02-08 20:02:58 +08:00
|
|
|
reuse_aliases = [
|
|
|
|
a for a, j in self.alias_map.items()
|
|
|
|
if (reuse is None or a in reuse) and j.equals(join)
|
|
|
|
]
|
2017-09-22 23:53:17 +08:00
|
|
|
if reuse_aliases:
|
2018-07-03 03:09:29 +08:00
|
|
|
if join.table_alias in reuse_aliases:
|
|
|
|
reuse_alias = join.table_alias
|
|
|
|
else:
|
|
|
|
# Reuse the most recent alias of the joined table
|
|
|
|
# (a many-to-many relation may be joined multiple times).
|
|
|
|
reuse_alias = reuse_aliases[-1]
|
|
|
|
self.ref_alias(reuse_alias)
|
|
|
|
return reuse_alias
|
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
|
|
|
|
|
|
|
# No reuse is possible, so we need a new alias.
|
2017-09-22 23:53:17 +08:00
|
|
|
alias, _ = self.table_alias(join.table_name, create=True, filtered_relation=join.filtered_relation)
|
2014-11-17 16:26:10 +08:00
|
|
|
if join.join_type:
|
|
|
|
if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:
|
|
|
|
join_type = LOUTER
|
|
|
|
else:
|
|
|
|
join_type = INNER
|
|
|
|
join.join_type = join_type
|
|
|
|
join.table_alias = alias
|
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
|
|
|
self.alias_map[alias] = join
|
|
|
|
return alias
|
|
|
|
|
2012-12-17 20:02:41 +08:00
|
|
|
def join_parent_model(self, opts, model, alias, seen):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Make sure the given 'model' is joined in the query. If 'model' isn't
|
2012-12-17 20:02:41 +08:00
|
|
|
a parent of 'opts' or if it is None this method is a no-op.
|
|
|
|
|
|
|
|
The 'alias' is the root alias for starting the join, 'seen' is a dict
|
2012-12-22 02:07:13 +08:00
|
|
|
of model -> alias of existing joins. It must also contain a mapping
|
|
|
|
of None -> some alias. This will be returned in the no-op case.
|
2012-12-17 20:02:41 +08:00
|
|
|
"""
|
|
|
|
if model in seen:
|
|
|
|
return seen[model]
|
|
|
|
chain = opts.get_base_chain(model)
|
2015-07-25 23:16:27 +08:00
|
|
|
if not chain:
|
2012-12-17 20:02:41 +08:00
|
|
|
return alias
|
2013-06-16 01:31:46 +08:00
|
|
|
curr_opts = opts
|
2012-12-17 20:02:41 +08:00
|
|
|
for int_model in chain:
|
|
|
|
if int_model in seen:
|
2014-12-01 15:28:01 +08:00
|
|
|
curr_opts = int_model._meta
|
|
|
|
alias = seen[int_model]
|
|
|
|
continue
|
2012-12-17 20:02:41 +08:00
|
|
|
# Proxy model have elements in base chain
|
|
|
|
# with no parents, assign the new options
|
|
|
|
# object and skip to the next base in that
|
|
|
|
# case
|
2013-06-16 01:31:46 +08:00
|
|
|
if not curr_opts.parents[int_model]:
|
|
|
|
curr_opts = int_model._meta
|
2012-12-17 20:02:41 +08:00
|
|
|
continue
|
2013-06-16 01:31:46 +08:00
|
|
|
link_field = curr_opts.get_ancestor_link(int_model)
|
2017-08-01 22:37:02 +08:00
|
|
|
join_info = self.setup_joins([link_field.name], curr_opts, alias)
|
2013-06-16 01:31:46 +08:00
|
|
|
curr_opts = int_model._meta
|
2017-08-01 22:37:02 +08:00
|
|
|
alias = seen[int_model] = join_info.joins[-1]
|
2012-12-22 02:07:13 +08:00
|
|
|
return alias or seen[None]
|
2012-12-17 20:02:41 +08:00
|
|
|
|
2020-06-15 02:38:43 +08:00
|
|
|
def add_annotation(self, annotation, alias, is_summary=False, select=True):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Add a single annotation expression to the Query."""
|
2014-11-18 17:24:33 +08:00
|
|
|
annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None,
|
|
|
|
summarize=is_summary)
|
2020-06-15 02:38:43 +08:00
|
|
|
if select:
|
|
|
|
self.append_annotation_mask([alias])
|
|
|
|
else:
|
|
|
|
self.set_annotation_mask(set(self.annotation_select).difference({alias}))
|
2013-12-25 21:13:18 +08:00
|
|
|
self.annotations[alias] = annotation
|
2009-01-15 19:06:34 +08:00
|
|
|
|
2017-04-23 15:01:47 +08:00
|
|
|
def resolve_expression(self, query, *args, **kwargs):
|
|
|
|
clone = self.clone()
|
|
|
|
# Subqueries need to use a different set of aliases than the outer query.
|
|
|
|
clone.bump_prefix(query)
|
|
|
|
clone.subquery = True
|
2019-03-06 14:05:55 +08:00
|
|
|
clone.where.resolve_expression(query, *args, **kwargs)
|
|
|
|
for key, value in clone.annotations.items():
|
|
|
|
resolved = value.resolve_expression(query, *args, **kwargs)
|
|
|
|
if hasattr(resolved, 'external_aliases'):
|
2019-12-17 14:21:13 +08:00
|
|
|
resolved.external_aliases.update(clone.external_aliases)
|
2019-03-06 14:05:55 +08:00
|
|
|
clone.annotations[key] = resolved
|
|
|
|
# Outer query's aliases are considered external.
|
2019-12-17 14:21:13 +08:00
|
|
|
for alias, table in query.alias_map.items():
|
|
|
|
clone.external_aliases[alias] = (
|
|
|
|
(isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias) or
|
|
|
|
(isinstance(table, BaseTable) and table.table_name != table.table_alias)
|
2019-03-06 14:05:55 +08:00
|
|
|
)
|
2017-04-23 15:01:47 +08:00
|
|
|
return clone
|
2016-10-28 23:20:23 +08:00
|
|
|
|
2019-12-17 14:21:13 +08:00
|
|
|
def get_external_cols(self):
|
|
|
|
exprs = chain(self.annotations.values(), self.where.children)
|
|
|
|
return [
|
2021-02-24 09:56:29 +08:00
|
|
|
col for col in self._gen_cols(exprs, include_external=True)
|
2019-12-17 14:21:13 +08:00
|
|
|
if col.alias in self.external_aliases
|
|
|
|
]
|
|
|
|
|
2017-04-28 09:30:37 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
2021-05-26 03:17:05 +08:00
|
|
|
# Some backends (e.g. Oracle) raise an error when a subquery contains
|
|
|
|
# unnecessary ORDER BY clause.
|
|
|
|
if (
|
|
|
|
self.subquery and
|
|
|
|
not connection.features.ignores_unnecessary_order_by_in_subqueries
|
|
|
|
):
|
|
|
|
self.clear_ordering(force=False)
|
2019-03-06 14:24:41 +08:00
|
|
|
sql, params = self.get_compiler(connection=connection).as_sql()
|
|
|
|
if self.subquery:
|
|
|
|
sql = '(%s)' % sql
|
|
|
|
return sql, params
|
2017-04-28 09:30:37 +08:00
|
|
|
|
2019-09-10 11:58:29 +08:00
|
|
|
def resolve_lookup_value(self, value, can_reuse, allow_joins):
|
2017-07-31 01:00:00 +08:00
|
|
|
if hasattr(value, 'resolve_expression'):
|
2019-09-10 11:58:29 +08:00
|
|
|
value = value.resolve_expression(
|
|
|
|
self, reuse=can_reuse, allow_joins=allow_joins,
|
|
|
|
)
|
2016-06-03 02:05:25 +08:00
|
|
|
elif isinstance(value, (list, tuple)):
|
|
|
|
# The items of the iterable may be expressions and therefore need
|
|
|
|
# to be resolved independently.
|
2020-10-23 17:33:10 +08:00
|
|
|
values = (
|
2019-09-10 11:58:29 +08:00
|
|
|
self.resolve_lookup_value(sub_value, can_reuse, allow_joins)
|
2019-11-10 16:48:36 +08:00
|
|
|
for sub_value in value
|
|
|
|
)
|
2020-10-23 17:33:10 +08:00
|
|
|
type_ = type(value)
|
|
|
|
if hasattr(type_, '_make'): # namedtuple
|
|
|
|
return type_(*values)
|
|
|
|
return type_(values)
|
2017-08-11 22:46:11 +08:00
|
|
|
return value
|
2013-08-13 19:11:52 +08:00
|
|
|
|
|
|
|
def solve_lookup_type(self, lookup):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').
|
2013-08-13 19:11:52 +08:00
|
|
|
"""
|
2014-01-18 17:09:43 +08:00
|
|
|
lookup_splitted = lookup.split(LOOKUP_SEP)
|
2019-02-05 19:22:08 +08:00
|
|
|
if self.annotations:
|
2015-06-05 18:10:51 +08:00
|
|
|
expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
|
|
|
|
if expression:
|
|
|
|
return expression_lookups, (), expression
|
2014-01-18 17:09:43 +08:00
|
|
|
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
|
|
|
|
field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
|
2017-07-31 01:00:00 +08:00
|
|
|
if len(lookup_parts) > 1 and not field_parts:
|
|
|
|
raise FieldError(
|
|
|
|
'Invalid lookup "%s" for model %s".' %
|
|
|
|
(lookup, self.get_meta().model.__name__)
|
|
|
|
)
|
2014-01-18 17:09:43 +08:00
|
|
|
return lookup_parts, field_parts, False
|
|
|
|
|
2015-06-25 23:31:07 +08:00
|
|
|
def check_query_object_type(self, value, opts, field):
|
2014-06-14 15:24:19 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Check whether the object passed while querying is of the correct type.
|
|
|
|
If not, raise a ValueError specifying the wrong object.
|
2014-06-14 15:24:19 +08:00
|
|
|
"""
|
|
|
|
if hasattr(value, '_meta'):
|
2015-06-25 23:31:07 +08:00
|
|
|
if not check_rel_lookup_compatibility(value._meta.model, opts, field):
|
2014-06-14 15:24:19 +08:00
|
|
|
raise ValueError(
|
|
|
|
'Cannot query "%s": Must be "%s" instance.' %
|
|
|
|
(value, opts.object_name))
|
|
|
|
|
|
|
|
def check_related_objects(self, field, value, opts):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Check the type of object passed to query relations."""
|
2015-02-26 21:44:41 +08:00
|
|
|
if field.is_relation:
|
2016-10-28 23:20:23 +08:00
|
|
|
# Check that the field and the queryset use the same model in a
|
|
|
|
# query like .filter(author=Author.objects.all()). For example, the
|
|
|
|
# opts would be Author's (from the author field) and value.model
|
|
|
|
# would be Author.objects.all() queryset's .model (Author also).
|
|
|
|
# The field is the related field on the lhs side.
|
2017-04-23 13:05:51 +08:00
|
|
|
if (isinstance(value, Query) and not value.has_select_fields and
|
2016-10-28 23:20:23 +08:00
|
|
|
not check_rel_lookup_compatibility(value.model, opts, field)):
|
|
|
|
raise ValueError(
|
|
|
|
'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' %
|
|
|
|
(value.model._meta.object_name, opts.object_name)
|
|
|
|
)
|
2014-10-28 09:36:47 +08:00
|
|
|
elif hasattr(value, '_meta'):
|
2015-06-25 23:31:07 +08:00
|
|
|
self.check_query_object_type(value, opts, field)
|
2014-09-02 21:30:53 +08:00
|
|
|
elif hasattr(value, '__iter__'):
|
|
|
|
for v in value:
|
2015-06-25 23:31:07 +08:00
|
|
|
self.check_query_object_type(v, opts, field)
|
2014-06-14 15:24:19 +08:00
|
|
|
|
2019-08-01 22:59:15 +08:00
|
|
|
def check_filterable(self, expression):
|
|
|
|
"""Raise an error if expression cannot be used in a WHERE clause."""
|
2020-06-06 03:01:39 +08:00
|
|
|
if (
|
|
|
|
hasattr(expression, 'resolve_expression') and
|
|
|
|
not getattr(expression, 'filterable', True)
|
|
|
|
):
|
2019-08-01 22:59:15 +08:00
|
|
|
raise NotSupportedError(
|
|
|
|
expression.__class__.__name__ + ' is disallowed in the filter '
|
|
|
|
'clause.'
|
|
|
|
)
|
|
|
|
if hasattr(expression, 'get_source_expressions'):
|
|
|
|
for expr in expression.get_source_expressions():
|
|
|
|
self.check_filterable(expr)
|
|
|
|
|
2014-01-18 17:09:43 +08:00
|
|
|
def build_lookup(self, lookups, lhs, rhs):
|
2014-11-10 21:38:03 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Try to extract transforms and lookup from given lhs.
|
2014-11-10 21:38:03 +08:00
|
|
|
|
|
|
|
The lhs value is something that works like SQLExpression.
|
|
|
|
The rhs value is what the lookup is going to compare against.
|
|
|
|
The lookups is a list of names to extract using get_lookup()
|
|
|
|
and get_transform().
|
|
|
|
"""
|
2017-07-31 01:00:00 +08:00
|
|
|
# __exact is the default lookup if one isn't given.
|
2018-09-28 21:57:12 +08:00
|
|
|
*transforms, lookup_name = lookups or ['exact']
|
|
|
|
for name in transforms:
|
2017-03-18 15:55:34 +08:00
|
|
|
lhs = self.try_transform(lhs, name)
|
2017-07-31 01:00:00 +08:00
|
|
|
# First try get_lookup() so that the lookup takes precedence if the lhs
|
|
|
|
# supports both transform and lookup for the name.
|
2017-12-06 18:58:02 +08:00
|
|
|
lookup_class = lhs.get_lookup(lookup_name)
|
2017-07-31 01:00:00 +08:00
|
|
|
if not lookup_class:
|
|
|
|
if lhs.field.is_relation:
|
2017-12-06 18:58:02 +08:00
|
|
|
raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))
|
2017-07-31 01:00:00 +08:00
|
|
|
# A lookup wasn't found. Try to interpret the name as a transform
|
|
|
|
# and do an Exact lookup against it.
|
2017-12-06 18:58:02 +08:00
|
|
|
lhs = self.try_transform(lhs, lookup_name)
|
|
|
|
lookup_name = 'exact'
|
|
|
|
lookup_class = lhs.get_lookup(lookup_name)
|
|
|
|
if not lookup_class:
|
|
|
|
return
|
2017-07-31 01:00:00 +08:00
|
|
|
|
|
|
|
lookup = lookup_class(lhs, rhs)
|
|
|
|
# Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
|
2018-02-20 23:47:12 +08:00
|
|
|
# uses of None as a query value unless the lookup supports it.
|
|
|
|
if lookup.rhs is None and not lookup.can_use_none_as_rhs:
|
2017-12-06 18:58:02 +08:00
|
|
|
if lookup_name not in ('exact', 'iexact'):
|
2017-07-31 01:00:00 +08:00
|
|
|
raise ValueError("Cannot use None as a query value")
|
|
|
|
return lhs.get_lookup('isnull')(lhs, True)
|
|
|
|
|
|
|
|
# For Oracle '' is equivalent to null. The check must be done at this
|
|
|
|
# stage because join promotion can't be done in the compiler. Using
|
|
|
|
# DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.
|
|
|
|
# A similar thing is done in is_nullable(), too.
|
2021-08-14 22:30:54 +08:00
|
|
|
if (
|
|
|
|
lookup_name == 'exact' and
|
|
|
|
lookup.rhs == '' and
|
|
|
|
connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls
|
|
|
|
):
|
2017-07-31 01:00:00 +08:00
|
|
|
return lhs.get_lookup('isnull')(lhs, True)
|
|
|
|
|
|
|
|
return lookup
|
2013-08-13 19:11:52 +08:00
|
|
|
|
2017-03-18 15:55:34 +08:00
|
|
|
def try_transform(self, lhs, name):
|
2014-11-10 21:38:03 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Helper method for build_lookup(). Try to fetch and initialize
|
2014-11-10 21:38:03 +08:00
|
|
|
a transform for name parameter from lhs.
|
|
|
|
"""
|
2015-08-03 10:30:06 +08:00
|
|
|
transform_class = lhs.get_transform(name)
|
|
|
|
if transform_class:
|
|
|
|
return transform_class(lhs)
|
2014-11-10 21:38:03 +08:00
|
|
|
else:
|
2018-09-29 15:22:27 +08:00
|
|
|
output_field = lhs.output_field.__class__
|
|
|
|
suggested_lookups = difflib.get_close_matches(name, output_field.get_lookups())
|
|
|
|
if suggested_lookups:
|
|
|
|
suggestion = ', perhaps you meant %s?' % ' or '.join(suggested_lookups)
|
|
|
|
else:
|
|
|
|
suggestion = '.'
|
2014-11-10 21:38:03 +08:00
|
|
|
raise FieldError(
|
|
|
|
"Unsupported lookup '%s' for %s or join on the field not "
|
2018-09-29 15:22:27 +08:00
|
|
|
"permitted%s" % (name, output_field.__name__, suggestion)
|
|
|
|
)
|
2014-11-10 21:38:03 +08:00
|
|
|
|
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
|
|
|
def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
|
2017-09-22 23:53:17 +08:00
|
|
|
can_reuse=None, allow_joins=True, split_subq=True,
|
2021-02-08 20:02:58 +08:00
|
|
|
check_filterable=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
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Build a WhereNode for a single filter clause but don't add it
|
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
|
|
|
to this Query. Query.add_q() will then add this filter to the where
|
2014-12-23 21:16:56 +08:00
|
|
|
Node.
|
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
|
|
|
|
|
|
|
The 'branch_negated' tells us if the current branch contains any
|
|
|
|
negations. This will be used to determine if subqueries are needed.
|
|
|
|
|
|
|
|
The 'current_negated' is used to determine if the current filter is
|
|
|
|
negated or not and this will be used to determine if IS NULL filtering
|
|
|
|
is needed.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
The difference between current_negated and branch_negated is that
|
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
|
|
|
branch_negated is set on first negation, but current_negated is
|
|
|
|
flipped for each negation.
|
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
|
|
|
|
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
|
|
|
Note that add_filter will not do any negating itself, that is done
|
|
|
|
upper in the code by add_q().
|
2008-04-28 12:29:06 +08:00
|
|
|
|
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
|
|
|
The 'can_reuse' is a set of reusable joins for multijoins.
|
|
|
|
|
|
|
|
The method will create a filter clause that can be added to the current
|
|
|
|
query. However, if the filter isn't added to the query then the caller
|
|
|
|
is responsible for unreffing the joins used.
|
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
|
|
|
"""
|
2015-04-14 06:57:11 +08:00
|
|
|
if isinstance(filter_expr, dict):
|
|
|
|
raise FieldError("Cannot parse keyword query as dict")
|
2019-11-15 13:08:36 +08:00
|
|
|
if isinstance(filter_expr, Q):
|
|
|
|
return self._add_q(
|
|
|
|
filter_expr,
|
|
|
|
branch_negated=branch_negated,
|
|
|
|
current_negated=current_negated,
|
|
|
|
used_aliases=can_reuse,
|
|
|
|
allow_joins=allow_joins,
|
|
|
|
split_subq=split_subq,
|
2019-12-06 00:08:47 +08:00
|
|
|
check_filterable=check_filterable,
|
2019-11-15 13:08:36 +08:00
|
|
|
)
|
2019-11-15 13:24:21 +08:00
|
|
|
if hasattr(filter_expr, 'resolve_expression'):
|
|
|
|
if not getattr(filter_expr, 'conditional', False):
|
|
|
|
raise TypeError('Cannot filter against a non-conditional expression.')
|
2021-04-03 01:25:20 +08:00
|
|
|
condition = filter_expr.resolve_expression(self, allow_joins=allow_joins)
|
|
|
|
if not isinstance(condition, Lookup):
|
|
|
|
condition = self.build_lookup(['exact'], condition, True)
|
2021-07-21 03:38:17 +08:00
|
|
|
return WhereNode([condition], connector=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
|
|
|
arg, value = filter_expr
|
2014-01-18 17:09:43 +08:00
|
|
|
if not arg:
|
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
|
|
|
raise FieldError("Cannot parse keyword query %r" % arg)
|
2015-06-05 18:10:51 +08:00
|
|
|
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
2019-12-06 00:08:47 +08:00
|
|
|
if check_filterable:
|
|
|
|
self.check_filterable(reffed_expression)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
if not allow_joins and len(parts) > 1:
|
|
|
|
raise FieldError("Joined field references are not permitted in this query")
|
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-08-11 22:46:11 +08:00
|
|
|
pre_joins = self.alias_refcount.copy()
|
2019-09-10 11:58:29 +08:00
|
|
|
value = self.resolve_lookup_value(value, can_reuse, allow_joins)
|
2017-08-11 22:46:11 +08:00
|
|
|
used_joins = {k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)}
|
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
|
|
|
|
2019-12-06 00:08:47 +08:00
|
|
|
if check_filterable:
|
|
|
|
self.check_filterable(value)
|
2019-08-01 22:59:15 +08:00
|
|
|
|
2015-06-05 18:10:51 +08:00
|
|
|
if reffed_expression:
|
|
|
|
condition = self.build_lookup(lookups, reffed_expression, value)
|
2021-07-21 03:38:17 +08:00
|
|
|
return WhereNode([condition], connector=AND), []
|
2009-01-15 19:06:34 +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
|
|
|
opts = self.get_meta()
|
|
|
|
alias = self.get_initial_alias()
|
2015-05-19 19:49:00 +08:00
|
|
|
allow_many = not branch_negated or not split_subq
|
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
|
|
|
|
|
|
|
try:
|
2017-09-22 23:53:17 +08:00
|
|
|
join_info = self.setup_joins(
|
|
|
|
parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many,
|
|
|
|
)
|
2014-06-14 15:24:19 +08:00
|
|
|
|
2015-04-28 06:23:56 +08:00
|
|
|
# Prevent iterator from being consumed by check_related_objects()
|
|
|
|
if isinstance(value, Iterator):
|
|
|
|
value = list(value)
|
2017-08-01 22:37:02 +08:00
|
|
|
self.check_related_objects(join_info.final_field, value, join_info.opts)
|
2014-06-14 15:24:19 +08:00
|
|
|
|
2014-04-28 20:27:36 +08:00
|
|
|
# split_exclude() needs to know which joins were generated for the
|
|
|
|
# lookup parts
|
2017-08-01 22:37:02 +08:00
|
|
|
self._lookup_joins = join_info.joins
|
2012-04-29 00:09:37 +08:00
|
|
|
except MultiJoin as e:
|
2018-01-13 08:06:15 +08:00
|
|
|
return self.split_exclude(filter_expr, can_reuse, e.names_with_path)
|
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
|
|
|
|
2016-10-27 06:01:37 +08:00
|
|
|
# Update used_joins before trimming since they are reused to determine
|
|
|
|
# which joins could be later promoted to INNER.
|
2017-08-01 22:37:02 +08:00
|
|
|
used_joins.update(join_info.joins)
|
|
|
|
targets, alias, join_list = self.trim_joins(join_info.targets, join_info.joins, join_info.path)
|
2016-10-27 06:01:37 +08:00
|
|
|
if can_reuse is not None:
|
|
|
|
can_reuse.update(join_list)
|
2013-03-25 00:40:40 +08:00
|
|
|
|
2017-08-01 22:37:02 +08:00
|
|
|
if join_info.final_field.is_relation:
|
2015-02-02 19:48:30 +08:00
|
|
|
# No support for transforms for relational fields
|
2015-10-26 07:29:34 +08:00
|
|
|
num_lookups = len(lookups)
|
|
|
|
if num_lookups > 1:
|
|
|
|
raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0]))
|
2015-02-02 19:48:30 +08:00
|
|
|
if len(targets) == 1:
|
2019-09-10 11:58:29 +08:00
|
|
|
col = self._get_col(targets[0], join_info.final_field, alias)
|
2015-02-02 19:48:30 +08:00
|
|
|
else:
|
2017-08-01 22:37:02 +08:00
|
|
|
col = MultiColSource(alias, targets, join_info.targets, join_info.final_field)
|
2015-02-02 19:48:30 +08:00
|
|
|
else:
|
2019-09-10 11:58:29 +08:00
|
|
|
col = self._get_col(targets[0], join_info.final_field, alias)
|
2014-01-18 17:09:43 +08:00
|
|
|
|
2017-07-31 01:00:00 +08:00
|
|
|
condition = self.build_lookup(lookups, col, value)
|
|
|
|
lookup_type = condition.lookup_name
|
2021-07-21 03:38:17 +08:00
|
|
|
clause = WhereNode([condition], connector=AND)
|
2013-11-05 00:04:57 +08:00
|
|
|
|
2017-07-31 01:00:00 +08:00
|
|
|
require_outer = lookup_type == 'isnull' and condition.rhs is True and not current_negated
|
2018-02-20 23:47:12 +08:00
|
|
|
if current_negated and (lookup_type != 'isnull' or condition.rhs is False) and condition.rhs is not None:
|
2013-11-05 00:04:57 +08:00
|
|
|
require_outer = True
|
2020-06-28 05:41:32 +08:00
|
|
|
if lookup_type != 'isnull':
|
2013-02-19 10:21:29 +08:00
|
|
|
# The condition added here will be SQL like this:
|
|
|
|
# NOT (col IS NOT NULL), where the first NOT is added in
|
|
|
|
# upper layers of code. The reason for addition is that if col
|
|
|
|
# is null, then col != someval will result in SQL "unknown"
|
|
|
|
# which isn't the same as in Python. The Python None handling
|
|
|
|
# is wanted, and it can be gotten by
|
|
|
|
# (col IS NULL OR col != someval)
|
|
|
|
# <=>
|
|
|
|
# NOT (col IS NOT NULL AND col = someval).
|
2020-06-28 05:41:32 +08:00
|
|
|
if (
|
|
|
|
self.is_nullable(targets[0]) or
|
|
|
|
self.alias_map[join_list[-1]].join_type == LOUTER
|
|
|
|
):
|
|
|
|
lookup_class = targets[0].get_lookup('isnull')
|
|
|
|
col = self._get_col(targets[0], join_info.targets[0], alias)
|
|
|
|
clause.add(lookup_class(col, False), AND)
|
|
|
|
# If someval is a nullable column, someval IS NOT NULL is
|
|
|
|
# added.
|
|
|
|
if isinstance(value, Col) and self.is_nullable(value.target):
|
|
|
|
lookup_class = value.target.get_lookup('isnull')
|
|
|
|
clause.add(lookup_class(value, False), AND)
|
2013-11-05 00:04:57 +08:00
|
|
|
return clause, used_joins if not require_outer else ()
|
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
|
|
|
|
2021-07-18 04:54:36 +08:00
|
|
|
def add_filter(self, filter_lhs, filter_rhs):
|
|
|
|
self.add_q(Q((filter_lhs, filter_rhs)))
|
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
|
|
|
|
|
|
|
def add_q(self, q_object):
|
|
|
|
"""
|
2014-12-23 21:16:56 +08:00
|
|
|
A preprocessor for the internal _add_q(). Responsible for doing final
|
|
|
|
join promotion.
|
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
|
|
|
"""
|
2013-11-05 00:04:57 +08:00
|
|
|
# For join promotion this case is doing an AND for the added q_object
|
|
|
|
# and existing conditions. So, any existing inner join forces the join
|
2013-11-30 17:19:24 +08:00
|
|
|
# type to remain inner. Existing outer joins can however be demoted.
|
2013-11-05 00:04:57 +08:00
|
|
|
# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
|
|
|
|
# rel_a doesn't produce any rows, then the whole condition must fail.
|
|
|
|
# So, demotion is OK.
|
2017-06-02 07:08:59 +08:00
|
|
|
existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}
|
2015-02-04 16:21:29 +08:00
|
|
|
clause, _ = self._add_q(q_object, self.used_aliases)
|
|
|
|
if clause:
|
|
|
|
self.where.add(clause, AND)
|
2013-11-05 00:04:57 +08:00
|
|
|
self.demote_joins(existing_inner)
|
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
|
|
|
|
2019-11-15 13:08:36 +08:00
|
|
|
def build_where(self, filter_expr):
|
|
|
|
return self.build_filter(filter_expr, allow_joins=False)[0]
|
2016-11-05 21:12:12 +08:00
|
|
|
|
2021-07-21 03:38:17 +08:00
|
|
|
def clear_where(self):
|
|
|
|
self.where = WhereNode()
|
|
|
|
|
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
|
|
|
def _add_q(self, q_object, used_aliases, branch_negated=False,
|
2019-12-06 00:08:47 +08:00
|
|
|
current_negated=False, allow_joins=True, split_subq=True,
|
|
|
|
check_filterable=True):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Add a Q-object to the current filter."""
|
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
|
|
|
connector = q_object.connector
|
|
|
|
current_negated = current_negated ^ q_object.negated
|
|
|
|
branch_negated = branch_negated or q_object.negated
|
2021-07-21 03:38:17 +08:00
|
|
|
target_clause = WhereNode(connector=connector, negated=q_object.negated)
|
2014-01-09 01:35:47 +08:00
|
|
|
joinpromoter = JoinPromoter(q_object.connector, len(q_object.children), current_negated)
|
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
|
|
|
for child in q_object.children:
|
2019-11-15 13:08:36 +08:00
|
|
|
child_clause, needed_inner = self.build_filter(
|
|
|
|
child, can_reuse=used_aliases, branch_negated=branch_negated,
|
|
|
|
current_negated=current_negated, allow_joins=allow_joins,
|
2019-12-06 00:08:47 +08:00
|
|
|
split_subq=split_subq, check_filterable=check_filterable,
|
2019-11-15 13:08:36 +08:00
|
|
|
)
|
|
|
|
joinpromoter.add_votes(needed_inner)
|
2015-02-04 16:21:29 +08:00
|
|
|
if child_clause:
|
|
|
|
target_clause.add(child_clause, connector)
|
2013-11-05 00:04:57 +08:00
|
|
|
needed_inner = joinpromoter.update_join_types(self)
|
|
|
|
return target_clause, needed_inner
|
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-09-22 23:53:17 +08:00
|
|
|
def build_filtered_relation_q(self, q_object, reuse, branch_negated=False, current_negated=False):
|
|
|
|
"""Add a FilteredRelation object to the current filter."""
|
|
|
|
connector = q_object.connector
|
|
|
|
current_negated ^= q_object.negated
|
|
|
|
branch_negated = branch_negated or q_object.negated
|
2021-07-21 03:38:17 +08:00
|
|
|
target_clause = WhereNode(connector=connector, negated=q_object.negated)
|
2017-09-22 23:53:17 +08:00
|
|
|
for child in q_object.children:
|
|
|
|
if isinstance(child, Node):
|
|
|
|
child_clause = self.build_filtered_relation_q(
|
|
|
|
child, reuse=reuse, branch_negated=branch_negated,
|
|
|
|
current_negated=current_negated,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
child_clause, _ = self.build_filter(
|
|
|
|
child, can_reuse=reuse, branch_negated=branch_negated,
|
|
|
|
current_negated=current_negated,
|
|
|
|
allow_joins=True, split_subq=False,
|
|
|
|
)
|
|
|
|
target_clause.add(child_clause, connector)
|
|
|
|
return target_clause
|
|
|
|
|
|
|
|
def add_filtered_relation(self, filtered_relation, alias):
|
|
|
|
filtered_relation.alias = alias
|
|
|
|
lookups = dict(get_children_from_q(filtered_relation.condition))
|
2020-01-07 07:44:32 +08:00
|
|
|
relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(filtered_relation.relation_name)
|
|
|
|
if relation_lookup_parts:
|
|
|
|
raise ValueError(
|
|
|
|
"FilteredRelation's relation_name cannot contain lookups "
|
|
|
|
"(got %r)." % filtered_relation.relation_name
|
|
|
|
)
|
|
|
|
for lookup in chain(lookups):
|
|
|
|
lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)
|
2017-09-22 23:53:17 +08:00
|
|
|
shift = 2 if not lookup_parts else 1
|
2020-01-07 07:44:32 +08:00
|
|
|
lookup_field_path = lookup_field_parts[:-shift]
|
|
|
|
for idx, lookup_field_part in enumerate(lookup_field_path):
|
|
|
|
if len(relation_field_parts) > idx:
|
|
|
|
if relation_field_parts[idx] != lookup_field_part:
|
|
|
|
raise ValueError(
|
|
|
|
"FilteredRelation's condition doesn't support "
|
|
|
|
"relations outside the %r (got %r)."
|
|
|
|
% (filtered_relation.relation_name, lookup)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
"FilteredRelation's condition doesn't support nested "
|
|
|
|
"relations deeper than the relation_name (got %r for "
|
|
|
|
"%r)." % (lookup, filtered_relation.relation_name)
|
|
|
|
)
|
2017-09-22 23:53:17 +08:00
|
|
|
self._filtered_relations[filtered_relation.alias] = filtered_relation
|
|
|
|
|
2014-01-18 17:09:43 +08:00
|
|
|
def names_to_path(self, names, opts, allow_many=True, fail_on_missing=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
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Walk the list of names and turns them into PathInfo tuples. A single
|
|
|
|
name in 'names' can generate multiple PathInfos (m2m, for example).
|
2012-11-24 22:19:55 +08:00
|
|
|
|
2013-11-30 17:19:24 +08:00
|
|
|
'names' is the path of names to travel, 'opts' is the model Options we
|
2013-06-19 02:14:07 +08:00
|
|
|
start the name resolving from, 'allow_many' is as for setup_joins().
|
2014-11-12 17:29:06 +08:00
|
|
|
If fail_on_missing is set to True, then a name that can't be resolved
|
|
|
|
will generate a FieldError.
|
2012-11-24 22:19:55 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a list of PathInfo tuples. In addition return the final field
|
|
|
|
(the last used join field) and target (which is a field guaranteed to
|
|
|
|
contain the same value as the final field). Finally, return those names
|
|
|
|
that weren't found (which are likely transforms and the final lookup).
|
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
|
|
|
"""
|
2013-02-18 07:56:24 +08:00
|
|
|
path, names_with_path = [], []
|
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
|
|
|
for pos, name in enumerate(names):
|
2014-01-21 00:28:16 +08:00
|
|
|
cur_names_with_path = (name, [])
|
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
|
|
|
if name == 'pk':
|
|
|
|
name = opts.pk.name
|
2015-08-15 02:22:08 +08:00
|
|
|
|
|
|
|
field = None
|
2017-09-22 23:53:17 +08:00
|
|
|
filtered_relation = None
|
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
|
|
|
try:
|
2015-01-07 08:16:35 +08:00
|
|
|
field = opts.get_field(name)
|
2015-08-15 02:22:08 +08:00
|
|
|
except FieldDoesNotExist:
|
|
|
|
if name in self.annotation_select:
|
|
|
|
field = self.annotation_select[name].output_field
|
2017-09-22 23:53:17 +08:00
|
|
|
elif name in self._filtered_relations and pos == 0:
|
|
|
|
filtered_relation = self._filtered_relations[name]
|
2020-01-07 07:44:32 +08:00
|
|
|
if LOOKUP_SEP in filtered_relation.relation_name:
|
|
|
|
parts = filtered_relation.relation_name.split(LOOKUP_SEP)
|
|
|
|
filtered_relation_path, field, _, _ = self.names_to_path(
|
|
|
|
parts, opts, allow_many, fail_on_missing,
|
|
|
|
)
|
|
|
|
path.extend(filtered_relation_path[:-1])
|
|
|
|
else:
|
|
|
|
field = opts.get_field(filtered_relation.relation_name)
|
2015-08-15 02:22:08 +08:00
|
|
|
if field is not None:
|
2015-01-07 08:16:35 +08:00
|
|
|
# Fields that contain one-to-many relations with a generic
|
|
|
|
# model (like a GenericForeignKey) cannot generate reverse
|
|
|
|
# relations and therefore cannot be used for reverse querying.
|
|
|
|
if field.is_relation and not field.related_model:
|
|
|
|
raise FieldError(
|
|
|
|
"Field %r does not generate an automatic reverse "
|
|
|
|
"relation and therefore cannot be used for reverse "
|
|
|
|
"querying. If it is a GenericForeignKey, consider "
|
|
|
|
"adding a GenericRelation." % name
|
|
|
|
)
|
2017-02-01 07:45:55 +08:00
|
|
|
try:
|
|
|
|
model = field.model._meta.concrete_model
|
|
|
|
except AttributeError:
|
|
|
|
# QuerySet.annotate() may introduce fields that aren't
|
|
|
|
# attached to a model.
|
|
|
|
model = None
|
2015-08-15 02:22:08 +08:00
|
|
|
else:
|
2014-09-07 06:13:46 +08:00
|
|
|
# We didn't find the current field, so move position back
|
2014-01-18 17:09:43 +08:00
|
|
|
# one step.
|
|
|
|
pos -= 1
|
2014-09-07 06:13:46 +08:00
|
|
|
if pos == -1 or fail_on_missing:
|
2018-09-28 21:57:12 +08:00
|
|
|
available = sorted([
|
|
|
|
*get_field_names_from_opts(opts),
|
|
|
|
*self.annotation_select,
|
|
|
|
*self._filtered_relations,
|
|
|
|
])
|
2016-09-17 21:29:14 +08:00
|
|
|
raise FieldError("Cannot resolve keyword '%s' into field. "
|
2014-09-07 06:13:46 +08:00
|
|
|
"Choices are: %s" % (name, ", ".join(available)))
|
2014-01-18 17:09:43 +08:00
|
|
|
break
|
2012-08-25 21:33:07 +08:00
|
|
|
# Check if we need any joins for concrete inheritance cases (the
|
|
|
|
# field lives in parent, but we are currently in one of its
|
|
|
|
# children)
|
2015-01-07 08:16:35 +08:00
|
|
|
if model is not opts.model:
|
2016-08-19 06:42:11 +08:00
|
|
|
path_to_parent = opts.get_path_to_parent(model)
|
|
|
|
if path_to_parent:
|
|
|
|
path.extend(path_to_parent)
|
|
|
|
cur_names_with_path[1].extend(path_to_parent)
|
|
|
|
opts = path_to_parent[-1].to_opts
|
2012-12-17 23:09:07 +08:00
|
|
|
if hasattr(field, 'get_path_info'):
|
2017-09-22 23:53:17 +08:00
|
|
|
pathinfos = field.get_path_info(filtered_relation)
|
2013-02-18 07:56:24 +08:00
|
|
|
if not allow_many:
|
|
|
|
for inner_pos, p in enumerate(pathinfos):
|
|
|
|
if p.m2m:
|
2014-01-21 00:28:16 +08:00
|
|
|
cur_names_with_path[1].extend(pathinfos[0:inner_pos + 1])
|
|
|
|
names_with_path.append(cur_names_with_path)
|
2013-02-18 07:56:24 +08:00
|
|
|
raise MultiJoin(pos + 1, names_with_path)
|
2013-03-25 00:40:40 +08:00
|
|
|
last = pathinfos[-1]
|
2012-12-17 23:09:07 +08:00
|
|
|
path.extend(pathinfos)
|
2013-03-25 00:40:40 +08:00
|
|
|
final_field = last.join_field
|
|
|
|
opts = last.to_opts
|
|
|
|
targets = last.target_fields
|
2014-01-21 00:28:16 +08:00
|
|
|
cur_names_with_path[1].extend(pathinfos)
|
|
|
|
names_with_path.append(cur_names_with_path)
|
2012-12-17 23:09:07 +08:00
|
|
|
else:
|
2012-08-25 21:33:07 +08:00
|
|
|
# Local non-relational field.
|
2013-03-25 00:40:40 +08:00
|
|
|
final_field = field
|
|
|
|
targets = (field,)
|
2014-09-07 06:13:46 +08:00
|
|
|
if fail_on_missing and pos + 1 != len(names):
|
|
|
|
raise FieldError(
|
|
|
|
"Cannot resolve keyword %r into field. Join on '%s'"
|
|
|
|
" not permitted." % (names[pos + 1], name))
|
2012-08-25 21:33:07 +08:00
|
|
|
break
|
2014-01-18 17:09:43 +08:00
|
|
|
return path, final_field, targets, names[pos + 1:]
|
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
|
|
|
|
2021-02-08 20:02:58 +08:00
|
|
|
def setup_joins(self, names, opts, alias, can_reuse=None, allow_many=True):
|
2009-03-06 10:02:09 +08:00
|
|
|
"""
|
2012-08-25 21:33:07 +08:00
|
|
|
Compute the necessary table joins for the passage through the fields
|
|
|
|
given in 'names'. 'opts' is the Options class for the current model
|
|
|
|
(which gives the table we are starting from), 'alias' is the alias for
|
|
|
|
the table to start the joining from.
|
|
|
|
|
|
|
|
The 'can_reuse' defines the reverse foreign key joins we can reuse. It
|
2012-12-21 03:25:48 +08:00
|
|
|
can be None in which case all joins are reusable or a set of aliases
|
|
|
|
that can be reused. Note that non-reverse foreign keys are always
|
|
|
|
reusable when using setup_joins().
|
2012-08-25 21:33:07 +08:00
|
|
|
|
|
|
|
If 'allow_many' is False, then any reverse foreign key seen will
|
|
|
|
generate a MultiJoin exception.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the final field involved in the joins, the target field (used
|
2017-06-18 23:53:40 +08:00
|
|
|
for any 'where' constraint), the final 'opts' value, the joins, the
|
|
|
|
field path traveled to generate the joins, and a transform function
|
|
|
|
that takes a field and alias and is equivalent to `field.get_col(alias)`
|
|
|
|
in the simple case but wraps field transforms if they were included in
|
|
|
|
names.
|
2009-03-06 10:02:09 +08:00
|
|
|
|
2012-08-25 21:33:07 +08:00
|
|
|
The target field is the field containing the concrete value. Final
|
|
|
|
field can be something different, for example foreign key pointing to
|
|
|
|
that value. Final field is needed for example in some value
|
|
|
|
conversions (convert 'obj' in fk__id=obj to pk val using the foreign
|
|
|
|
key field for example).
|
|
|
|
"""
|
|
|
|
joins = [alias]
|
2017-06-18 23:53:40 +08:00
|
|
|
# The transform can't be applied yet, as joins must be trimmed later.
|
|
|
|
# To avoid making every caller of this method look up transforms
|
2018-07-18 23:54:15 +08:00
|
|
|
# directly, compute transforms here and create a partial that converts
|
|
|
|
# fields to the appropriate wrapped version.
|
2017-06-18 23:53:40 +08:00
|
|
|
|
|
|
|
def final_transformer(field, alias):
|
2020-11-16 06:43:47 +08:00
|
|
|
if not self.alias_cols:
|
|
|
|
alias = None
|
2017-06-18 23:53:40 +08:00
|
|
|
return field.get_col(alias)
|
|
|
|
|
|
|
|
# Try resolving all the names as fields first. If there's an error,
|
|
|
|
# treat trailing names as lookups until a field can be resolved.
|
|
|
|
last_field_exception = None
|
|
|
|
for pivot in range(len(names), 0, -1):
|
|
|
|
try:
|
|
|
|
path, final_field, targets, rest = self.names_to_path(
|
|
|
|
names[:pivot], opts, allow_many, fail_on_missing=True,
|
|
|
|
)
|
|
|
|
except FieldError as exc:
|
|
|
|
if pivot == 1:
|
|
|
|
# The first item cannot be a lookup, so it's safe
|
|
|
|
# to raise the field error here.
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
last_field_exception = exc
|
|
|
|
else:
|
|
|
|
# The transforms are the remaining items that couldn't be
|
|
|
|
# resolved into fields.
|
|
|
|
transforms = names[pivot:]
|
|
|
|
break
|
|
|
|
for name in transforms:
|
|
|
|
def transform(field, alias, *, name, previous):
|
|
|
|
try:
|
|
|
|
wrapped = previous(field, alias)
|
|
|
|
return self.try_transform(wrapped, name)
|
|
|
|
except FieldError:
|
|
|
|
# FieldError is raised if the transform doesn't exist.
|
|
|
|
if isinstance(final_field, Field) and last_field_exception:
|
|
|
|
raise last_field_exception
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
final_transformer = functools.partial(transform, name=name, previous=final_transformer)
|
2012-08-25 21:33:07 +08:00
|
|
|
# Then, add the path to the query's joins. Note that we can't trim
|
|
|
|
# joins at this stage - we will need the information about join type
|
|
|
|
# of the trimmed joins.
|
2014-11-12 19:22:08 +08:00
|
|
|
for join in path:
|
2017-09-22 23:53:17 +08:00
|
|
|
if join.filtered_relation:
|
|
|
|
filtered_relation = join.filtered_relation.clone()
|
|
|
|
table_alias = filtered_relation.alias
|
|
|
|
else:
|
|
|
|
filtered_relation = None
|
|
|
|
table_alias = None
|
2012-12-17 23:09:07 +08:00
|
|
|
opts = join.to_opts
|
|
|
|
if join.direct:
|
2013-03-25 00:40:40 +08:00
|
|
|
nullable = self.is_nullable(join.join_field)
|
2012-08-25 21:33:07 +08:00
|
|
|
else:
|
|
|
|
nullable = True
|
2017-09-22 23:53:17 +08:00
|
|
|
connection = Join(
|
|
|
|
opts.db_table, alias, table_alias, INNER, join.join_field,
|
|
|
|
nullable, filtered_relation=filtered_relation,
|
|
|
|
)
|
2021-02-08 20:02:58 +08:00
|
|
|
reuse = can_reuse if join.m2m else None
|
|
|
|
alias = self.join(connection, reuse=reuse)
|
2012-08-25 21:33:07 +08:00
|
|
|
joins.append(alias)
|
2017-09-22 23:53:17 +08:00
|
|
|
if filtered_relation:
|
|
|
|
filtered_relation.path = joins[:]
|
2017-06-18 23:53:40 +08:00
|
|
|
return JoinInfo(final_field, targets, opts, joins, path, final_transformer)
|
2009-03-06 10:02:09 +08:00
|
|
|
|
2013-03-25 00:40:40 +08:00
|
|
|
def trim_joins(self, targets, joins, path):
|
2012-08-25 21:33:07 +08:00
|
|
|
"""
|
|
|
|
The 'target' parameter is the final field being joined to, 'joins'
|
|
|
|
is the full list of join aliases. The 'path' contain the PathInfos
|
|
|
|
used to create the joins.
|
2011-08-23 11:38:42 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the final target field and table alias and the new active
|
2012-08-25 21:33:07 +08:00
|
|
|
joins.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Always trim any direct join if the target column is already in the
|
|
|
|
previous table. Can't trim reverse joins as it's unknown if there's
|
|
|
|
anything on the other side of the join.
|
2012-08-25 21:33:07 +08:00
|
|
|
"""
|
2013-11-05 00:04:57 +08:00
|
|
|
joins = joins[:]
|
2013-03-25 00:40:40 +08:00
|
|
|
for pos, info in enumerate(reversed(path)):
|
|
|
|
if len(joins) == 1 or not info.direct:
|
2009-01-15 19:06:34 +08:00
|
|
|
break
|
2017-09-22 23:53:17 +08:00
|
|
|
if info.filtered_relation:
|
|
|
|
break
|
2017-06-02 07:08:59 +08:00
|
|
|
join_targets = {t.column for t in info.join_field.foreign_related_fields}
|
|
|
|
cur_targets = {t.column for t in targets}
|
2013-03-25 00:40:40 +08:00
|
|
|
if not cur_targets.issubset(join_targets):
|
|
|
|
break
|
2016-04-18 20:59:01 +08:00
|
|
|
targets_dict = {r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets}
|
|
|
|
targets = tuple(targets_dict[t.column] for t in targets)
|
2013-03-25 00:40:40 +08:00
|
|
|
self.unref_alias(joins.pop())
|
|
|
|
return targets, joins[-1], joins
|
2009-01-15 19:06:34 +08:00
|
|
|
|
2019-06-28 03:13:48 +08:00
|
|
|
@classmethod
|
2021-02-24 09:56:29 +08:00
|
|
|
def _gen_cols(cls, exprs, include_external=False):
|
2019-06-28 03:13:48 +08:00
|
|
|
for expr in exprs:
|
|
|
|
if isinstance(expr, Col):
|
2019-12-17 14:21:13 +08:00
|
|
|
yield expr
|
2021-02-24 09:56:29 +08:00
|
|
|
elif include_external and callable(getattr(expr, 'get_external_cols', None)):
|
|
|
|
yield from expr.get_external_cols()
|
2021-09-01 04:37:07 +08:00
|
|
|
elif hasattr(expr, 'get_source_expressions'):
|
2021-02-24 09:56:29 +08:00
|
|
|
yield from cls._gen_cols(
|
|
|
|
expr.get_source_expressions(),
|
|
|
|
include_external=include_external,
|
|
|
|
)
|
2019-12-17 14:21:13 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _gen_col_aliases(cls, exprs):
|
|
|
|
yield from (expr.alias for expr in cls._gen_cols(exprs))
|
2019-06-28 03:13:48 +08:00
|
|
|
|
2019-09-10 11:58:29 +08:00
|
|
|
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
|
2019-06-28 03:13:48 +08:00
|
|
|
annotation = self.annotations.get(name)
|
|
|
|
if annotation is not None:
|
|
|
|
if not allow_joins:
|
|
|
|
for alias in self._gen_col_aliases([annotation]):
|
|
|
|
if isinstance(self.alias_map[alias], Join):
|
|
|
|
raise FieldError(
|
|
|
|
'Joined field references are not permitted in '
|
|
|
|
'this query'
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
if summarize:
|
2014-11-20 20:30:25 +08:00
|
|
|
# Summarize currently means we are doing an aggregate() query
|
|
|
|
# which is executed as a wrapped subquery if any of the
|
|
|
|
# aggregate() elements reference an existing annotation. In
|
|
|
|
# that case we need to return a Ref to the subquery's annotation.
|
2020-06-15 02:38:43 +08:00
|
|
|
if name not in self.annotation_select:
|
|
|
|
raise FieldError(
|
|
|
|
"Cannot aggregate over the '%s' alias. Use annotate() "
|
|
|
|
"to promote it." % name
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
return Ref(name, self.annotation_select[name])
|
|
|
|
else:
|
2019-06-28 03:13:48 +08:00
|
|
|
return annotation
|
2013-12-25 21:13:18 +08:00
|
|
|
else:
|
|
|
|
field_list = name.split(LOOKUP_SEP)
|
2020-11-16 06:43:47 +08:00
|
|
|
annotation = self.annotations.get(field_list[0])
|
|
|
|
if annotation is not None:
|
|
|
|
for transform in field_list[1:]:
|
|
|
|
annotation = self.try_transform(annotation, transform)
|
|
|
|
return annotation
|
2017-09-22 23:53:17 +08:00
|
|
|
join_info = self.setup_joins(field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse)
|
2018-09-07 04:10:20 +08:00
|
|
|
targets, final_alias, join_list = self.trim_joins(join_info.targets, join_info.joins, join_info.path)
|
2019-01-16 13:39:49 +08:00
|
|
|
if not allow_joins and len(join_list) > 1:
|
|
|
|
raise FieldError('Joined field references are not permitted in this query')
|
2013-12-25 21:13:18 +08:00
|
|
|
if len(targets) > 1:
|
|
|
|
raise FieldError("Referencing multicolumn fields with F() objects "
|
|
|
|
"isn't supported")
|
2018-09-07 04:10:20 +08:00
|
|
|
# Verify that the last lookup in name is a field or a transform:
|
|
|
|
# transform_function() raises FieldError if not.
|
2020-11-16 06:43:47 +08:00
|
|
|
transform = join_info.transform_function(targets[0], final_alias)
|
2013-12-25 21:13:18 +08:00
|
|
|
if reuse is not None:
|
|
|
|
reuse.update(join_list)
|
2020-11-16 06:43:47 +08:00
|
|
|
return transform
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2018-01-13 08:06:15 +08:00
|
|
|
def split_exclude(self, filter_expr, can_reuse, names_with_path):
|
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
|
|
|
"""
|
|
|
|
When doing an exclude against any kind of N-to-many relation, we need
|
|
|
|
to use a subquery. This method constructs the nested query, given the
|
|
|
|
original exclude filter (filter_expr) and the portion up to the first
|
|
|
|
N-to-many relation field.
|
2012-08-21 04:03:58 +08:00
|
|
|
|
2018-01-13 08:06:15 +08:00
|
|
|
For example, if the origin filter is ~Q(child__name='foo'), filter_expr
|
|
|
|
is ('child__name', 'foo') and can_reuse is a set of joins usable for
|
|
|
|
filters in the original query.
|
2012-08-21 04:03:58 +08:00
|
|
|
|
2013-02-18 07:56:24 +08:00
|
|
|
We will turn this into equivalent of:
|
2020-10-26 04:04:21 +08:00
|
|
|
WHERE NOT EXISTS(
|
|
|
|
SELECT 1
|
|
|
|
FROM child
|
|
|
|
WHERE name = 'foo' AND child.parent_id = parent.id
|
|
|
|
LIMIT 1
|
|
|
|
)
|
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
|
|
|
"""
|
2013-02-18 07:56:24 +08:00
|
|
|
# Generate the inner query.
|
2009-12-22 23:18:51 +08:00
|
|
|
query = Query(self.model)
|
2019-05-06 22:42:56 +08:00
|
|
|
query._filtered_relations = self._filtered_relations
|
2021-07-18 04:54:36 +08:00
|
|
|
filter_lhs, filter_rhs = filter_expr
|
|
|
|
if isinstance(filter_rhs, OuterRef):
|
|
|
|
filter_rhs = OuterRef(filter_rhs)
|
|
|
|
elif isinstance(filter_rhs, F):
|
|
|
|
filter_rhs = OuterRef(filter_rhs.name)
|
|
|
|
query.add_filter(filter_lhs, filter_rhs)
|
2021-05-27 04:09:15 +08:00
|
|
|
query.clear_ordering(force=True)
|
2013-02-18 07:56:24 +08:00
|
|
|
# Try to have as simple as possible subquery -> trim leading joins from
|
|
|
|
# the subquery.
|
2013-06-06 05:29:44 +08:00
|
|
|
trimmed_prefix, contains_louter = query.trim_start(names_with_path)
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
col = query.select[0]
|
2015-02-15 03:37:12 +08:00
|
|
|
select_field = col.target
|
2014-12-01 15:28:01 +08:00
|
|
|
alias = col.alias
|
2013-11-03 04:35:45 +08:00
|
|
|
if alias in can_reuse:
|
2014-01-18 17:09:43 +08:00
|
|
|
pk = select_field.model._meta.pk
|
2013-11-03 04:35:45 +08:00
|
|
|
# Need to add a restriction so that outer query's filters are in effect for
|
|
|
|
# the subquery, too.
|
|
|
|
query.bump_prefix(self)
|
2014-01-18 17:09:43 +08:00
|
|
|
lookup_class = select_field.get_lookup('exact')
|
2014-12-01 15:28:01 +08:00
|
|
|
# Note that the query.select[0].alias is different from alias
|
|
|
|
# due to bump_prefix above.
|
|
|
|
lookup = lookup_class(pk.get_col(query.select[0].alias),
|
|
|
|
pk.get_col(alias))
|
2014-01-18 17:09:43 +08:00
|
|
|
query.where.add(lookup, AND)
|
2019-12-17 14:21:13 +08:00
|
|
|
query.external_aliases[alias] = True
|
2011-02-08 22:06:02 +08:00
|
|
|
|
2020-10-26 04:04:21 +08:00
|
|
|
lookup_class = select_field.get_lookup('exact')
|
|
|
|
lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))
|
|
|
|
query.where.add(lookup, AND)
|
|
|
|
condition, needed_inner = self.build_filter(Exists(query))
|
|
|
|
|
2013-06-06 05:29:44 +08:00
|
|
|
if contains_louter:
|
2013-11-05 00:04:57 +08:00
|
|
|
or_null_condition, _ = self.build_filter(
|
2013-06-06 05:29:44 +08:00
|
|
|
('%s__isnull' % trimmed_prefix, True),
|
|
|
|
current_negated=True, branch_negated=True, can_reuse=can_reuse)
|
|
|
|
condition.add(or_null_condition, OR)
|
|
|
|
# Note that the end result will be:
|
|
|
|
# (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL.
|
|
|
|
# This might look crazy but due to how IN works, this seems to be
|
|
|
|
# correct. If the IS NOT NULL check is removed then outercol NOT
|
|
|
|
# IN will return UNKNOWN. If the IS NULL check is removed, then if
|
|
|
|
# outercol IS NULL we will not match the row.
|
2013-11-05 00:04:57 +08:00
|
|
|
return condition, needed_inner
|
2013-02-18 07:56:24 +08:00
|
|
|
|
2012-10-24 05:04:37 +08:00
|
|
|
def set_empty(self):
|
2014-12-23 21:16:56 +08:00
|
|
|
self.where.add(NothingNode(), AND)
|
2020-07-07 18:15:05 +08:00
|
|
|
for query in self.combined_queries:
|
|
|
|
query.set_empty()
|
2012-10-24 05:04:37 +08:00
|
|
|
|
|
|
|
def is_empty(self):
|
2014-12-23 21:16:56 +08:00
|
|
|
return any(isinstance(c, NothingNode) for c in self.where.children)
|
2012-10-24 05:04:37 +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
|
|
|
def set_limits(self, low=None, high=None):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Adjust the limits on the rows retrieved. Use low/high to set these,
|
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
|
|
|
as it makes it more Pythonic to read and write. When the SQL query is
|
2017-01-25 07:04:12 +08:00
|
|
|
created, convert them to the appropriate offset and limit values.
|
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-01-25 07:04:12 +08:00
|
|
|
Apply any limits passed in here to the existing constraints. Add low
|
|
|
|
to the current low value and clamp both to any existing high value.
|
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
|
|
|
"""
|
2008-07-11 20:43:27 +08:00
|
|
|
if high is not None:
|
2008-10-08 16:37:35 +08:00
|
|
|
if self.high_mark is not None:
|
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
|
|
|
self.high_mark = min(self.high_mark, self.low_mark + high)
|
|
|
|
else:
|
|
|
|
self.high_mark = self.low_mark + high
|
2008-07-11 20:43:27 +08:00
|
|
|
if low is not None:
|
2008-10-08 16:37:35 +08:00
|
|
|
if self.high_mark is not None:
|
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
|
|
|
self.low_mark = min(self.high_mark, self.low_mark + low)
|
|
|
|
else:
|
|
|
|
self.low_mark = self.low_mark + low
|
|
|
|
|
2015-12-18 03:16:43 +08:00
|
|
|
if self.low_mark == self.high_mark:
|
|
|
|
self.set_empty()
|
|
|
|
|
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 clear_limits(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Clear any existing limits."""
|
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
|
|
|
self.low_mark, self.high_mark = 0, None
|
|
|
|
|
2019-07-26 02:45:55 +08:00
|
|
|
@property
|
|
|
|
def is_sliced(self):
|
|
|
|
return self.low_mark != 0 or self.high_mark is not None
|
|
|
|
|
2017-10-16 23:10:21 +08:00
|
|
|
def has_limit_one(self):
|
|
|
|
return self.high_mark is not None and (self.high_mark - self.low_mark) == 1
|
|
|
|
|
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 can_filter(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return True if adding filters to this instance is still possible.
|
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
|
|
|
|
|
|
|
Typically, this means no limits or offsets have been put on the results.
|
|
|
|
"""
|
2019-07-26 02:45:55 +08:00
|
|
|
return not self.is_sliced
|
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
|
|
|
|
2012-10-10 20:58:39 +08:00
|
|
|
def clear_select_clause(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Remove all fields from SELECT clause."""
|
2017-03-08 22:25:44 +08:00
|
|
|
self.select = ()
|
2012-10-10 20:58:39 +08:00
|
|
|
self.default_cols = False
|
|
|
|
self.select_related = False
|
|
|
|
self.set_extra_mask(())
|
2013-12-25 21:13:18 +08:00
|
|
|
self.set_annotation_mask(())
|
2012-10-10 20:58:39 +08:00
|
|
|
|
2009-01-08 13:49:03 +08:00
|
|
|
def clear_select_fields(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Clear the list of fields to select (but not extra_select columns).
|
2009-01-08 13:49:03 +08:00
|
|
|
Some queryset types completely replace any existing list of select
|
|
|
|
columns.
|
|
|
|
"""
|
2017-03-08 22:25:44 +08:00
|
|
|
self.select = ()
|
|
|
|
self.values_select = ()
|
2014-12-01 15:28:01 +08:00
|
|
|
|
2020-10-10 23:41:13 +08:00
|
|
|
def add_select_col(self, col, name):
|
2019-03-28 02:18:18 +08:00
|
|
|
self.select += col,
|
2020-10-10 23:41:13 +08:00
|
|
|
self.values_select += name,
|
2019-03-28 02:18:18 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def set_select(self, cols):
|
|
|
|
self.default_cols = False
|
2017-03-08 22:25:44 +08:00
|
|
|
self.select = tuple(cols)
|
2014-12-01 15:28:01 +08:00
|
|
|
|
2011-12-23 04:42:40 +08:00
|
|
|
def add_distinct_fields(self, *field_names):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add and resolve the given fields to the query's "distinct on" clause.
|
2011-12-23 04:42:40 +08:00
|
|
|
"""
|
|
|
|
self.distinct_fields = field_names
|
|
|
|
self.distinct = 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
|
|
|
def add_fields(self, field_names, allow_m2m=True):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add the given (model) fields to the select set. Add the field names in
|
|
|
|
the order specified.
|
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
|
|
|
"""
|
|
|
|
alias = self.get_initial_alias()
|
|
|
|
opts = self.get_meta()
|
2009-01-15 19:06:34 +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
|
|
|
try:
|
2017-03-08 22:25:44 +08:00
|
|
|
cols = []
|
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
|
|
|
for name in field_names:
|
2013-09-25 00:37:55 +08:00
|
|
|
# Join promotion note - we must not remove any rows here, so
|
|
|
|
# if there is no existing joins, use outer join.
|
2017-08-01 22:37:02 +08:00
|
|
|
join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
|
|
|
|
targets, final_alias, joins = self.trim_joins(
|
|
|
|
join_info.targets,
|
|
|
|
join_info.joins,
|
|
|
|
join_info.path,
|
|
|
|
)
|
2013-03-25 00:40:40 +08:00
|
|
|
for target in targets:
|
2017-06-18 23:53:40 +08:00
|
|
|
cols.append(join_info.transform_function(target, final_alias))
|
2017-03-08 22:25:44 +08:00
|
|
|
if cols:
|
|
|
|
self.set_select(cols)
|
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
|
|
|
except MultiJoin:
|
|
|
|
raise FieldError("Invalid field name: '%s'" % name)
|
|
|
|
except FieldError:
|
2012-07-17 22:01:01 +08:00
|
|
|
if LOOKUP_SEP in name:
|
2012-07-17 17:24:56 +08:00
|
|
|
# For lookups spanning over relationships, show the error
|
|
|
|
# from the model on which the lookup failed.
|
|
|
|
raise
|
2020-06-15 02:38:43 +08:00
|
|
|
elif name in self.annotations:
|
|
|
|
raise FieldError(
|
|
|
|
"Cannot select the '%s' alias. Use annotate() to promote "
|
|
|
|
"it." % name
|
|
|
|
)
|
2012-07-17 17:24:56 +08:00
|
|
|
else:
|
2018-09-28 21:57:12 +08:00
|
|
|
names = sorted([
|
|
|
|
*get_field_names_from_opts(opts), *self.extra,
|
|
|
|
*self.annotation_select, *self._filtered_relations
|
|
|
|
])
|
2012-07-17 17:24:56 +08:00
|
|
|
raise FieldError("Cannot resolve keyword %r into field. "
|
|
|
|
"Choices are: %s" % (name, ", ".join(names)))
|
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 add_ordering(self, *ordering):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add items from the 'ordering' sequence to the query's "order by"
|
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
|
|
|
clause. These items are either field names (not column names) --
|
2015-01-09 23:16:16 +08:00
|
|
|
possibly with a direction prefix ('-' or '?') -- or OrderBy
|
|
|
|
expressions.
|
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-01-25 07:04:12 +08:00
|
|
|
If 'ordering' is empty, clear all ordering from the query.
|
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
|
|
|
"""
|
|
|
|
errors = []
|
|
|
|
for item in ordering:
|
2020-04-06 03:45:06 +08:00
|
|
|
if isinstance(item, str):
|
|
|
|
if item == '?':
|
|
|
|
continue
|
|
|
|
if item.startswith('-'):
|
|
|
|
item = item[1:]
|
|
|
|
if item in self.annotations:
|
|
|
|
continue
|
|
|
|
if self.extra and item in self.extra:
|
|
|
|
continue
|
|
|
|
# names_to_path() validates the lookup. A descriptive
|
|
|
|
# FieldError will be raise if it's not.
|
|
|
|
self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)
|
2020-04-06 03:32:54 +08:00
|
|
|
elif not hasattr(item, 'resolve_expression'):
|
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
|
|
|
errors.append(item)
|
2015-06-04 22:50:14 +08:00
|
|
|
if getattr(item, 'contains_aggregate', False):
|
|
|
|
raise FieldError(
|
|
|
|
'Using an aggregate in order_by() without also including '
|
|
|
|
'it in annotate() is not allowed: %s' % item
|
|
|
|
)
|
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
|
|
|
if errors:
|
|
|
|
raise FieldError('Invalid order_by arguments: %s' % errors)
|
|
|
|
if ordering:
|
2017-03-08 22:25:44 +08:00
|
|
|
self.order_by += ordering
|
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
|
|
|
else:
|
|
|
|
self.default_ordering = False
|
|
|
|
|
2021-05-27 04:09:15 +08:00
|
|
|
def clear_ordering(self, force=False, clear_default=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
|
|
|
"""
|
2021-05-27 04:09:15 +08:00
|
|
|
Remove any ordering settings if the current query allows it without
|
|
|
|
side effects, set 'force' to True to clear the ordering regardless.
|
|
|
|
If 'clear_default' is True, there will be no ordering in the resulting
|
|
|
|
query (not even the model's default).
|
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
|
|
|
"""
|
2021-05-27 04:09:15 +08:00
|
|
|
if not force and (self.is_sliced or self.distinct_fields or self.select_for_update):
|
|
|
|
return
|
2017-03-08 22:25:44 +08:00
|
|
|
self.order_by = ()
|
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
|
|
|
self.extra_order_by = ()
|
2021-05-27 04:09:15 +08:00
|
|
|
if clear_default:
|
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
|
|
|
self.default_ordering = False
|
|
|
|
|
2019-12-22 12:22:49 +08:00
|
|
|
def set_group_by(self, allow_aliases=True):
|
2009-01-15 19:06:34 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Expand the GROUP BY clause required by the query.
|
2009-01-15 19:06:34 +08:00
|
|
|
|
|
|
|
This will usually be the set of all non-aggregate fields in the
|
|
|
|
return data. If the database backend supports grouping by the
|
|
|
|
primary key, and the query would be equivalent, the optimization
|
|
|
|
will be made automatically.
|
|
|
|
"""
|
2020-03-20 02:54:36 +08:00
|
|
|
# Column names from JOINs to check collisions with aliases.
|
|
|
|
if allow_aliases:
|
|
|
|
column_names = set()
|
|
|
|
seen_models = set()
|
|
|
|
for join in list(self.alias_map.values())[1:]: # Skip base table.
|
|
|
|
model = join.join_field.related_model
|
|
|
|
if model not in seen_models:
|
|
|
|
column_names.update({
|
|
|
|
field.column
|
|
|
|
for field in model._meta.local_concrete_fields
|
|
|
|
})
|
|
|
|
seen_models.add(model)
|
|
|
|
|
2017-03-08 22:25:44 +08:00
|
|
|
group_by = list(self.select)
|
2015-07-16 05:29:33 +08:00
|
|
|
if self.annotation_select:
|
2019-03-19 13:05:47 +08:00
|
|
|
for alias, annotation in self.annotation_select.items():
|
2021-01-07 14:55:06 +08:00
|
|
|
if not allow_aliases or alias in column_names:
|
|
|
|
alias = None
|
|
|
|
group_by_cols = annotation.get_group_by_cols(alias=alias)
|
2019-03-19 13:05:47 +08:00
|
|
|
group_by.extend(group_by_cols)
|
2017-03-08 22:25:44 +08:00
|
|
|
self.group_by = tuple(group_by)
|
2013-12-25 21:13:18 +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
|
|
|
def add_select_related(self, fields):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Set up the select_related data structure so that we only select
|
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
|
|
|
certain related models (as opposed to all models, when
|
|
|
|
self.select_related=True).
|
|
|
|
"""
|
2013-10-15 20:15:02 +08:00
|
|
|
if isinstance(self.select_related, bool):
|
|
|
|
field_dict = {}
|
|
|
|
else:
|
|
|
|
field_dict = self.select_related
|
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
|
|
|
for field in fields:
|
|
|
|
d = field_dict
|
|
|
|
for part in field.split(LOOKUP_SEP):
|
|
|
|
d = d.setdefault(part, {})
|
|
|
|
self.select_related = field_dict
|
|
|
|
|
|
|
|
def add_extra(self, select, select_params, where, params, tables, order_by):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add data to the various extra_* attributes for user-created additions
|
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
|
|
|
to the query.
|
|
|
|
"""
|
|
|
|
if select:
|
2008-08-18 04:07:59 +08:00
|
|
|
# We need to pair any placeholder markers in the 'select'
|
|
|
|
# dictionary with their parameters in 'select_params' so that
|
|
|
|
# subsequent updates to the select dictionary also adjust the
|
|
|
|
# parameters appropriately.
|
2019-02-05 19:22:08 +08:00
|
|
|
select_pairs = {}
|
2008-08-18 04:07:59 +08:00
|
|
|
if select_params:
|
|
|
|
param_iter = iter(select_params)
|
|
|
|
else:
|
|
|
|
param_iter = iter([])
|
|
|
|
for name, entry in select.items():
|
2018-10-09 02:47:01 +08:00
|
|
|
entry = str(entry)
|
2008-08-18 04:07:59 +08:00
|
|
|
entry_params = []
|
|
|
|
pos = entry.find("%s")
|
|
|
|
while pos != -1:
|
2014-09-10 15:23:58 +08:00
|
|
|
if pos == 0 or entry[pos - 1] != '%':
|
|
|
|
entry_params.append(next(param_iter))
|
2008-08-18 04:07:59 +08:00
|
|
|
pos = entry.find("%s", pos + 2)
|
|
|
|
select_pairs[name] = (entry, entry_params)
|
2009-04-30 23:40:09 +08:00
|
|
|
self.extra.update(select_pairs)
|
2010-02-23 12:39:39 +08:00
|
|
|
if where or params:
|
|
|
|
self.where.add(ExtraWhere(where, params), 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
|
|
|
if tables:
|
|
|
|
self.extra_tables += tuple(tables)
|
|
|
|
if order_by:
|
|
|
|
self.extra_order_by = order_by
|
|
|
|
|
2009-03-19 17:06:04 +08:00
|
|
|
def clear_deferred_loading(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Remove any fields from the deferred loading set."""
|
2017-03-08 22:25:44 +08:00
|
|
|
self.deferred_loading = (frozenset(), True)
|
2009-03-19 17:06:04 +08:00
|
|
|
|
|
|
|
def add_deferred_loading(self, field_names):
|
|
|
|
"""
|
|
|
|
Add the given list of model field names to the set of fields to
|
|
|
|
exclude from loading from the database when automatic column selection
|
2017-01-25 07:04:12 +08:00
|
|
|
is done. Add the new field names to any existing field names that
|
2009-03-19 17:06:04 +08:00
|
|
|
are deferred (or removed from any existing field names that are marked
|
|
|
|
as the only ones for immediate loading).
|
|
|
|
"""
|
|
|
|
# Fields on related models are stored in the literal double-underscore
|
|
|
|
# format, so that we can use a set datastructure. We do the foo__bar
|
2014-03-02 22:25:53 +08:00
|
|
|
# splitting and handling when computing the SQL column names (as part of
|
2009-03-19 17:06:04 +08:00
|
|
|
# get_columns()).
|
|
|
|
existing, defer = self.deferred_loading
|
|
|
|
if defer:
|
|
|
|
# Add to existing deferred names.
|
|
|
|
self.deferred_loading = existing.union(field_names), True
|
|
|
|
else:
|
|
|
|
# Remove names from the set of any existing "immediate load" names.
|
2021-07-20 05:02:52 +08:00
|
|
|
if new_existing := existing.difference(field_names):
|
|
|
|
self.deferred_loading = new_existing, False
|
|
|
|
else:
|
|
|
|
self.clear_deferred_loading()
|
|
|
|
if new_only := set(field_names).difference(existing):
|
|
|
|
self.deferred_loading = new_only, True
|
2009-03-19 17:06:04 +08:00
|
|
|
|
|
|
|
def add_immediate_loading(self, field_names):
|
|
|
|
"""
|
|
|
|
Add the given list of model field names to the set of fields to
|
|
|
|
retrieve when the SQL is executed ("immediate loading" fields). The
|
|
|
|
field names replace any existing immediate loading field names. If
|
2017-01-25 07:04:12 +08:00
|
|
|
there are field names already specified for deferred loading, remove
|
|
|
|
those names from the new field_names before storing the new names
|
2009-03-19 17:06:04 +08:00
|
|
|
for immediate loading. (That is, immediate loading overrides any
|
|
|
|
existing immediate values, but respects existing deferrals.)
|
|
|
|
"""
|
|
|
|
existing, defer = self.deferred_loading
|
2011-08-23 14:29:01 +08:00
|
|
|
field_names = set(field_names)
|
|
|
|
if 'pk' in field_names:
|
|
|
|
field_names.remove('pk')
|
2013-05-14 03:40:39 +08:00
|
|
|
field_names.add(self.get_meta().pk.name)
|
2011-08-23 14:29:01 +08:00
|
|
|
|
2009-03-19 17:06:04 +08:00
|
|
|
if defer:
|
|
|
|
# Remove any existing deferred names from the current set before
|
|
|
|
# setting the new names.
|
2011-08-23 14:29:01 +08:00
|
|
|
self.deferred_loading = field_names.difference(existing), False
|
2009-03-19 17:06:04 +08:00
|
|
|
else:
|
|
|
|
# Replace any existing "immediate load" field names.
|
2017-03-08 22:25:44 +08:00
|
|
|
self.deferred_loading = frozenset(field_names), False
|
2009-03-19 17:06:04 +08:00
|
|
|
|
|
|
|
def get_loaded_field_names(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
If any fields are marked to be deferred, return a dictionary mapping
|
2009-03-19 17:06:04 +08:00
|
|
|
models to a set of names in those fields that will be loaded. If a
|
2014-04-27 01:18:45 +08:00
|
|
|
model is not in the returned dictionary, none of its fields are
|
2009-03-19 17:06:04 +08:00
|
|
|
deferred.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
If no fields are marked for deferral, return an empty dictionary.
|
2009-03-19 17:06:04 +08:00
|
|
|
"""
|
2012-06-26 23:08:42 +08:00
|
|
|
# We cache this because we call this function multiple times
|
|
|
|
# (compiler.fill_related_selections, query.iterator)
|
|
|
|
try:
|
|
|
|
return self._loaded_field_names_cache
|
|
|
|
except AttributeError:
|
|
|
|
collection = {}
|
|
|
|
self.deferred_to_data(collection, self.get_loaded_field_names_cb)
|
|
|
|
self._loaded_field_names_cache = collection
|
|
|
|
return collection
|
2009-03-19 17:06:04 +08:00
|
|
|
|
|
|
|
def get_loaded_field_names_cb(self, target, model, fields):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Callback used by get_deferred_field_names()."""
|
2014-12-01 15:28:01 +08:00
|
|
|
target[model] = {f.attname for f in fields}
|
2009-03-19 17:06:04 +08:00
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def set_annotation_mask(self, names):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Set the mask of annotations that will be returned by the SELECT."""
|
2009-04-30 23:40:09 +08:00
|
|
|
if names is None:
|
2013-12-25 21:13:18 +08:00
|
|
|
self.annotation_select_mask = None
|
2009-04-30 23:40:09 +08:00
|
|
|
else:
|
2013-12-25 21:13:18 +08:00
|
|
|
self.annotation_select_mask = set(names)
|
|
|
|
self._annotation_select_cache = None
|
2009-02-23 22:47:59 +08:00
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def append_annotation_mask(self, names):
|
|
|
|
if self.annotation_select_mask is not None:
|
2017-08-15 21:43:47 +08:00
|
|
|
self.set_annotation_mask(self.annotation_select_mask.union(names))
|
2013-07-23 16:38:38 +08:00
|
|
|
|
2009-04-30 23:40:09 +08:00
|
|
|
def set_extra_mask(self, names):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Set the mask of extra select items that will be returned by SELECT.
|
|
|
|
Don't remove them from the Query since they might be used later.
|
2009-04-30 23:40:09 +08:00
|
|
|
"""
|
|
|
|
if names is None:
|
|
|
|
self.extra_select_mask = None
|
|
|
|
else:
|
|
|
|
self.extra_select_mask = set(names)
|
|
|
|
self._extra_select_cache = None
|
|
|
|
|
2016-08-15 13:49:33 +08:00
|
|
|
def set_values(self, fields):
|
|
|
|
self.select_related = False
|
|
|
|
self.clear_deferred_loading()
|
|
|
|
self.clear_select_fields()
|
|
|
|
|
|
|
|
if fields:
|
|
|
|
field_names = []
|
|
|
|
extra_names = []
|
|
|
|
annotation_names = []
|
2019-02-05 19:22:08 +08:00
|
|
|
if not self.extra and not self.annotations:
|
2016-08-15 13:49:33 +08:00
|
|
|
# Shortcut - if there are no extra or annotations, then
|
|
|
|
# the values() clause must be just field names.
|
|
|
|
field_names = list(fields)
|
|
|
|
else:
|
|
|
|
self.default_cols = False
|
|
|
|
for f in fields:
|
|
|
|
if f in self.extra_select:
|
|
|
|
extra_names.append(f)
|
|
|
|
elif f in self.annotation_select:
|
|
|
|
annotation_names.append(f)
|
|
|
|
else:
|
|
|
|
field_names.append(f)
|
|
|
|
self.set_extra_mask(extra_names)
|
|
|
|
self.set_annotation_mask(annotation_names)
|
2020-10-28 02:13:10 +08:00
|
|
|
selected = frozenset(field_names + extra_names + annotation_names)
|
2016-08-15 13:49:33 +08:00
|
|
|
else:
|
|
|
|
field_names = [f.attname for f in self.model._meta.concrete_fields]
|
2020-10-28 02:13:10 +08:00
|
|
|
selected = frozenset(field_names)
|
2020-01-15 16:32:42 +08:00
|
|
|
# Selected annotations must be known before setting the GROUP BY
|
|
|
|
# clause.
|
|
|
|
if self.group_by is True:
|
|
|
|
self.add_fields((f.attname for f in self.model._meta.concrete_fields), False)
|
|
|
|
# Disable GROUP BY aliases to avoid orphaning references to the
|
|
|
|
# SELECT clause which is about to be cleared.
|
|
|
|
self.set_group_by(allow_aliases=False)
|
|
|
|
self.clear_select_fields()
|
2020-05-14 11:38:29 +08:00
|
|
|
elif self.group_by:
|
|
|
|
# Resolve GROUP BY annotation references if they are not part of
|
|
|
|
# the selected fields anymore.
|
|
|
|
group_by = []
|
|
|
|
for expr in self.group_by:
|
2020-10-28 02:13:10 +08:00
|
|
|
if isinstance(expr, Ref) and expr.refs not in selected:
|
2020-05-14 11:38:29 +08:00
|
|
|
expr = self.annotations[expr.refs]
|
|
|
|
group_by.append(expr)
|
|
|
|
self.group_by = tuple(group_by)
|
2016-08-15 13:49:33 +08:00
|
|
|
|
2017-03-08 22:25:44 +08:00
|
|
|
self.values_select = tuple(field_names)
|
2016-08-15 13:49:33 +08:00
|
|
|
self.add_fields(field_names, True)
|
|
|
|
|
2013-08-21 19:25:19 +08:00
|
|
|
@property
|
2013-12-25 21:13:18 +08:00
|
|
|
def annotation_select(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""
|
2019-02-05 19:22:08 +08:00
|
|
|
Return the dictionary of aggregate columns that are not masked and
|
2017-01-25 07:04:12 +08:00
|
|
|
should be used in the SELECT clause. Cache this result for performance.
|
2009-02-23 22:47:59 +08:00
|
|
|
"""
|
2013-12-25 21:13:18 +08:00
|
|
|
if self._annotation_select_cache is not None:
|
|
|
|
return self._annotation_select_cache
|
2019-02-05 19:22:08 +08:00
|
|
|
elif not self.annotations:
|
2013-08-21 19:25:19 +08:00
|
|
|
return {}
|
2013-12-25 21:13:18 +08:00
|
|
|
elif self.annotation_select_mask is not None:
|
2019-02-05 19:22:08 +08:00
|
|
|
self._annotation_select_cache = {
|
|
|
|
k: v for k, v in self.annotations.items()
|
2013-12-25 21:13:18 +08:00
|
|
|
if k in self.annotation_select_mask
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2013-12-25 21:13:18 +08:00
|
|
|
return self._annotation_select_cache
|
2009-02-23 22:47:59 +08:00
|
|
|
else:
|
2013-12-25 21:13:18 +08:00
|
|
|
return self.annotations
|
|
|
|
|
2013-08-21 19:25:19 +08:00
|
|
|
@property
|
|
|
|
def extra_select(self):
|
2009-04-30 23:40:09 +08:00
|
|
|
if self._extra_select_cache is not None:
|
|
|
|
return self._extra_select_cache
|
2019-02-05 19:22:08 +08:00
|
|
|
if not self.extra:
|
2013-08-21 19:25:19 +08:00
|
|
|
return {}
|
2009-04-30 23:40:09 +08:00
|
|
|
elif self.extra_select_mask is not None:
|
2019-02-05 19:22:08 +08:00
|
|
|
self._extra_select_cache = {
|
|
|
|
k: v for k, v in self.extra.items()
|
2009-04-30 23:40:09 +08:00
|
|
|
if k in self.extra_select_mask
|
2019-02-05 19:22:08 +08:00
|
|
|
}
|
2009-04-30 23:40:09 +08:00
|
|
|
return self._extra_select_cache
|
|
|
|
else:
|
|
|
|
return self.extra
|
|
|
|
|
2013-02-18 07:56:24 +08:00
|
|
|
def trim_start(self, names_with_path):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Trim joins from the start of the join path. The candidates for trim
|
2013-06-06 05:29:44 +08:00
|
|
|
are the PathInfos in names_with_path structure that are m2m joins.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Also set the select column so the start matches the join.
|
2013-06-06 05:29:44 +08:00
|
|
|
|
|
|
|
This method is meant to be used for generating the subquery joins &
|
|
|
|
cols in split_exclude().
|
2013-02-18 07:56:24 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a lookup usable for doing outerq.filter(lookup=self) and a
|
|
|
|
boolean indicating if the joins in the prefix contain a LEFT OUTER join.
|
2013-02-18 07:56:24 +08:00
|
|
|
_"""
|
2013-03-25 00:40:40 +08:00
|
|
|
all_paths = []
|
2013-02-18 07:56:24 +08:00
|
|
|
for _, paths in names_with_path:
|
2013-03-25 00:40:40 +08:00
|
|
|
all_paths.extend(paths)
|
2013-06-06 05:29:44 +08:00
|
|
|
contains_louter = False
|
2014-04-28 20:27:36 +08:00
|
|
|
# Trim and operate only on tables that were generated for
|
|
|
|
# the lookup part of the query. That is, avoid trimming
|
|
|
|
# joins generated for F() expressions.
|
2017-06-28 14:23:37 +08:00
|
|
|
lookup_tables = [
|
|
|
|
t for t in self.alias_map
|
|
|
|
if t in self._lookup_joins or t == self.base_table
|
|
|
|
]
|
2014-04-28 20:27:36 +08:00
|
|
|
for trimmed_paths, path in enumerate(all_paths):
|
2013-06-06 05:29:44 +08:00
|
|
|
if path.m2m:
|
|
|
|
break
|
2014-11-17 16:26:10 +08:00
|
|
|
if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:
|
2013-06-06 05:29:44 +08:00
|
|
|
contains_louter = True
|
2014-11-17 16:26:10 +08:00
|
|
|
alias = lookup_tables[trimmed_paths]
|
|
|
|
self.unref_alias(alias)
|
2013-06-06 05:29:44 +08:00
|
|
|
# The path.join_field is a Rel, lets get the other side's field
|
|
|
|
join_field = path.join_field.field
|
|
|
|
# Build the filter prefix.
|
2014-04-28 20:27:36 +08:00
|
|
|
paths_in_prefix = trimmed_paths
|
2013-06-06 05:29:44 +08:00
|
|
|
trimmed_prefix = []
|
|
|
|
for name, path in names_with_path:
|
|
|
|
if paths_in_prefix - len(path) < 0:
|
2013-03-25 00:40:40 +08:00
|
|
|
break
|
2013-06-06 05:29:44 +08:00
|
|
|
trimmed_prefix.append(name)
|
|
|
|
paths_in_prefix -= len(path)
|
|
|
|
trimmed_prefix.append(
|
|
|
|
join_field.foreign_related_fields[0].name)
|
|
|
|
trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
|
|
|
|
# Lets still see if we can trim the first join from the inner query
|
2019-05-06 22:42:56 +08:00
|
|
|
# (that is, self). We can't do this for:
|
|
|
|
# - LEFT JOINs because we would miss those rows that have nothing on
|
|
|
|
# the outer side,
|
|
|
|
# - INNER JOINs from filtered relations because we would miss their
|
|
|
|
# filters.
|
|
|
|
first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]
|
|
|
|
if first_join.join_type != LOUTER and not first_join.filtered_relation:
|
2013-06-06 05:29:44 +08:00
|
|
|
select_fields = [r[0] for r in join_field.related_fields]
|
2014-04-28 20:27:36 +08:00
|
|
|
select_alias = lookup_tables[trimmed_paths + 1]
|
|
|
|
self.unref_alias(lookup_tables[trimmed_paths])
|
2021-07-21 03:38:17 +08:00
|
|
|
extra_restriction = join_field.get_extra_restriction(None, lookup_tables[trimmed_paths + 1])
|
2013-06-06 05:29:44 +08:00
|
|
|
if extra_restriction:
|
|
|
|
self.where.add(extra_restriction, AND)
|
|
|
|
else:
|
|
|
|
# TODO: It might be possible to trim more joins from the start of the
|
|
|
|
# inner query if it happens to have a longer join chain containing the
|
|
|
|
# values in select_fields. Lets punt this one for now.
|
|
|
|
select_fields = [r[1] for r in join_field.related_fields]
|
2014-04-28 20:27:36 +08:00
|
|
|
select_alias = lookup_tables[trimmed_paths]
|
2014-11-17 16:26:10 +08:00
|
|
|
# The found starting point is likely a Join instead of a BaseTable reference.
|
|
|
|
# But the first entry in the query's FROM clause must not be a JOIN.
|
2017-06-28 14:23:37 +08:00
|
|
|
for table in self.alias_map:
|
2014-11-17 16:26:10 +08:00
|
|
|
if self.alias_refcount[table] > 0:
|
|
|
|
self.alias_map[table] = BaseTable(self.alias_map[table].table_name, table)
|
|
|
|
break
|
2014-12-01 15:28:01 +08:00
|
|
|
self.set_select([f.get_col(select_alias) for f in select_fields])
|
2013-06-06 05:29:44 +08:00
|
|
|
return trimmed_prefix, contains_louter
|
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
|
|
|
|
2012-04-30 00:25:46 +08:00
|
|
|
def is_nullable(self, field):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Check if the given field should be treated as nullable.
|
2012-04-30 00:25:46 +08:00
|
|
|
|
|
|
|
Some backends treat '' as null and Django treats such fields as
|
|
|
|
nullable for those backends. In such situations field.null can be
|
|
|
|
False even if we should treat the field as nullable.
|
|
|
|
"""
|
|
|
|
# We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
|
|
|
|
# (nor should it have) knowledge of which connection is going to be
|
|
|
|
# used. The proper fix would be to defer all decisions where
|
|
|
|
# is_nullable() is needed to the compiler stage, but that is not easy
|
|
|
|
# to do currently.
|
2018-01-04 07:52:12 +08:00
|
|
|
return (
|
|
|
|
connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
|
|
|
|
field.empty_strings_allowed
|
|
|
|
) or field.null
|
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
|
|
|
|
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
|
|
|
def get_order_dir(field, default='ASC'):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the field name and direction for an order specification. For
|
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
|
|
|
example, '-foo' is returned as ('foo', 'DESC').
|
|
|
|
|
|
|
|
The 'default' param is used to indicate which way no prefix (or a '+'
|
|
|
|
prefix) should sort. The '-' prefix always sorts the opposite way.
|
|
|
|
"""
|
|
|
|
dirn = ORDER_DIR[default]
|
|
|
|
if field[0] == '-':
|
|
|
|
return field[1:], dirn[1]
|
|
|
|
return field, dirn[0]
|
|
|
|
|
|
|
|
|
2009-03-19 17:06:04 +08:00
|
|
|
def add_to_dict(data, key, value):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Add "value" to the set of values for "key", whether or not "key" already
|
|
|
|
exists.
|
2009-03-19 17:06:04 +08:00
|
|
|
"""
|
|
|
|
if key in data:
|
|
|
|
data[key].add(value)
|
|
|
|
else:
|
2014-09-26 20:31:50 +08:00
|
|
|
data[key] = {value}
|
2012-11-29 00:16:00 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2012-11-29 00:16:00 +08:00
|
|
|
def is_reverse_o2o(field):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Check if the given field is reverse-o2o. The field is expected to be some
|
|
|
|
sort of relation field or related object.
|
2012-11-29 00:16:00 +08:00
|
|
|
"""
|
2015-02-02 19:48:30 +08:00
|
|
|
return field.is_relation and field.one_to_one and not field.concrete
|
2012-08-25 19:13:37 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class JoinPromoter:
|
2013-11-05 00:04:57 +08:00
|
|
|
"""
|
|
|
|
A class to abstract away join promotion problems for complex filter
|
|
|
|
conditions.
|
|
|
|
"""
|
|
|
|
|
2014-01-09 01:35:47 +08:00
|
|
|
def __init__(self, connector, num_children, negated):
|
2013-11-05 00:04:57 +08:00
|
|
|
self.connector = connector
|
2014-01-09 01:35:47 +08:00
|
|
|
self.negated = negated
|
|
|
|
if self.negated:
|
|
|
|
if connector == AND:
|
|
|
|
self.effective_connector = OR
|
|
|
|
else:
|
|
|
|
self.effective_connector = AND
|
|
|
|
else:
|
|
|
|
self.effective_connector = self.connector
|
2013-11-05 00:04:57 +08:00
|
|
|
self.num_children = num_children
|
|
|
|
# Maps of table alias to how many times it is seen as required for
|
|
|
|
# inner and/or outer joins.
|
2015-09-06 22:40:02 +08:00
|
|
|
self.votes = Counter()
|
2013-11-05 00:04:57 +08:00
|
|
|
|
2015-09-06 22:40:02 +08:00
|
|
|
def add_votes(self, votes):
|
2013-11-05 00:04:57 +08:00
|
|
|
"""
|
2015-09-06 22:40:02 +08:00
|
|
|
Add single vote per item to self.votes. Parameter can be any
|
2013-11-05 00:04:57 +08:00
|
|
|
iterable.
|
|
|
|
"""
|
2015-09-06 22:40:02 +08:00
|
|
|
self.votes.update(votes)
|
2013-11-05 00:04:57 +08:00
|
|
|
|
|
|
|
def update_join_types(self, query):
|
|
|
|
"""
|
|
|
|
Change join types so that the generated query is as efficient as
|
|
|
|
possible, but still correct. So, change as many joins as possible
|
|
|
|
to INNER, but don't make OUTER joins INNER if that could remove
|
|
|
|
results from the query.
|
|
|
|
"""
|
|
|
|
to_promote = set()
|
|
|
|
to_demote = set()
|
2014-01-09 01:35:47 +08:00
|
|
|
# The effective_connector is used so that NOT (a AND b) is treated
|
|
|
|
# similarly to (a OR b) for join promotion.
|
2015-09-06 22:40:02 +08:00
|
|
|
for table, votes in self.votes.items():
|
2013-11-05 00:04:57 +08:00
|
|
|
# We must use outer joins in OR case when the join isn't contained
|
|
|
|
# in all of the joins. Otherwise the INNER JOIN itself could remove
|
|
|
|
# valid results. Consider the case where a model with rel_a and
|
|
|
|
# rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
|
|
|
|
# if rel_a join doesn't produce any results is null (for example
|
|
|
|
# reverse foreign key or null value in direct foreign key), and
|
|
|
|
# there is a matching row in rel_b with col=2, then an INNER join
|
|
|
|
# to rel_a would remove a valid match from the query. So, we need
|
|
|
|
# to promote any existing INNER to LOUTER (it is possible this
|
|
|
|
# promotion in turn will be demoted later on).
|
2014-01-09 01:35:47 +08:00
|
|
|
if self.effective_connector == 'OR' and votes < self.num_children:
|
2013-11-05 00:04:57 +08:00
|
|
|
to_promote.add(table)
|
|
|
|
# If connector is AND and there is a filter that can match only
|
|
|
|
# when there is a joinable row, then use INNER. For example, in
|
|
|
|
# rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
|
|
|
|
# as join output, then the col=1 or col=2 can't match (as
|
|
|
|
# NULL=anything is always false).
|
|
|
|
# For the OR case, if all children voted for a join to be inner,
|
|
|
|
# then we can use INNER for the join. For example:
|
|
|
|
# (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
|
|
|
|
# then if rel_a doesn't produce any rows, the whole condition
|
|
|
|
# can't match. Hence we can safely use INNER join.
|
2014-01-09 01:35:47 +08:00
|
|
|
if self.effective_connector == 'AND' or (
|
|
|
|
self.effective_connector == 'OR' and votes == self.num_children):
|
2013-11-05 00:04:57 +08:00
|
|
|
to_demote.add(table)
|
|
|
|
# Finally, what happens in cases where we have:
|
|
|
|
# (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
|
|
|
|
# Now, we first generate the OR clause, and promote joins for it
|
|
|
|
# in the first if branch above. Both rel_a and rel_b are promoted
|
|
|
|
# to LOUTER joins. After that we do the AND case. The OR case
|
|
|
|
# voted no inner joins but the rel_a__col__gte=0 votes inner join
|
|
|
|
# for rel_a. We demote it back to INNER join (in AND case a single
|
|
|
|
# vote is enough). The demotion is OK, if rel_a doesn't produce
|
|
|
|
# rows, then the rel_a__col__gte=0 clause can't be true, and thus
|
|
|
|
# the whole clause must be false. So, it is safe to use INNER
|
|
|
|
# join.
|
|
|
|
# Note that in this example we could just as well have the __gte
|
|
|
|
# clause and the OR clause swapped. Or we could replace the __gte
|
2014-05-29 08:39:14 +08:00
|
|
|
# clause with an OR clause containing rel_a__col=1|rel_a__col=2,
|
2013-11-05 00:04:57 +08:00
|
|
|
# and again we could safely demote to INNER.
|
|
|
|
query.promote_joins(to_promote)
|
|
|
|
query.demote_joins(to_demote)
|
|
|
|
return to_demote
|