desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Changes the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause.'
def change_aliases(self, change_map):
assert (set(change_map.keys()).intersection(set(change_map.values())) == set()) self.where.relabel_aliases(change_map) self.having.relabel_aliases(change_map) for columns in [self.select, (self.group_by or [])]: for (pos, col) in enumerate(columns): if isinstance(col, (list, tuple)):...
'Changes the alias prefix to the next letter in the alphabet and relabels all the aliases. Even tables that previously had no alias will get an alias after this call (it\'s mostly used for nested queries and the outer query will already be using the non-aliased table name). Subclasses who create their own prefix should...
def bump_prefix(self, exceptions=()):
current = ord(self.alias_prefix) assert (current < ord('Z')) prefix = chr((current + 1)) self.alias_prefix = prefix change_map = SortedDict() for (pos, alias) in enumerate(self.tables): if (alias in exceptions): continue new_alias = ('%s%d' % (prefix, pos)) ch...
'Returns the first alias for this query, after increasing its reference count.'
def get_initial_alias(self):
if self.tables: alias = self.tables[0] self.ref_alias(alias) else: alias = self.join((None, self.model._meta.db_table, None, None)) return alias
'Returns the number of tables in this query with a non-zero reference count. Note that after execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method.'
def count_active_tables(self):
return len([1 for count in self.alias_refcount.values() if count])
'Returns an alias for the join in \'connection\', either reusing an existing alias for that join or creating a new one. \'connection\' is a tuple (lhs, table, lhs_col, col) where \'lhs\' is either an existing table alias or a table name. The join correspods to the SQL equivalent of:: lhs.lhs_col = table.col If \'always...
def join(self, connection, always_create=False, exclusions=(), promote=False, outer_if_first=False, nullable=False, reuse=None):
(lhs, table, lhs_col, col) = connection if (lhs in self.alias_map): lhs_table = self.alias_map[lhs].table_name else: lhs_table = lhs if (reuse and always_create and (table in self.table_map)): exclusions = set(self.table_map[table]).difference(reuse).union(set(exclusions)) ...
'If the model that is the basis for this QuerySet inherits other models, we need to ensure that those other models have their tables included in the query. We do this as a separate step so that subclasses know which tables are going to be active in the query, without needing to compute all the select columns (this meth...
def setup_inherited_models(self):
opts = self.model._meta.concrete_model._meta root_alias = self.tables[0] seen = {None: root_alias} for (field, model) in opts.get_fields_with_model(): if (model not in seen): link_field = opts.get_ancestor_link(model) seen[model] = self.join((root_alias, model._meta.db_ta...
'Undoes the effects of setup_inherited_models(). Should be called whenever select columns (self.select) are set explicitly.'
def remove_inherited_models(self):
for (key, alias) in self.included_inherited_models.items(): if key: self.unref_alias(alias) self.included_inherited_models = {}
'Returns whether or not all elements of this q_object need to be put together in the HAVING clause.'
def need_force_having(self, q_object):
for child in q_object.children: if isinstance(child, Node): if self.need_force_having(child): return True elif (child[0].split(LOOKUP_SEP)[0] in self.aggregates): return True return False
'Adds a single aggregate expression to the Query'
def add_aggregate(self, aggregate, model, alias, is_summary):
opts = model._meta field_list = aggregate.lookup.split(LOOKUP_SEP) if ((len(field_list) == 1) and (aggregate.lookup in self.aggregates)): field_name = field_list[0] col = field_name source = self.aggregates[field_name] if (not is_summary): raise FieldError(("Canno...
'Add a single filter to the query. The \'filter_expr\' is a pair: (filter_string, value). E.g. (\'name__contains\', \'fred\') If \'negate\' is True, this is an exclude() filter. It\'s important to note that this method does not negate anything in the where-clause object when inserting the filter constraints. This is be...
def add_filter(self, filter_expr, connector=AND, negate=False, trim=False, can_reuse=None, process_extras=True, force_having=False):
(arg, value) = filter_expr parts = arg.split(LOOKUP_SEP) if (not parts): raise FieldError(('Cannot parse keyword query %r' % arg)) lookup_type = 'exact' num_parts = len(parts) if ((len(parts) > 1) and (parts[(-1)] in self.query_terms) and (arg not in self.aggregates)): ...
'Adds a Q-object to the current filter. Can also be used to add anything that has an \'add_to_query()\' method.'
def add_q(self, q_object, used_aliases=None, force_having=False):
if (used_aliases is None): used_aliases = self.used_aliases if hasattr(q_object, 'add_to_query'): q_object.add_to_query(self, used_aliases) else: if (self.where and (q_object.connector != AND) and (len(q_object) > 1)): self.where.start_subtree(AND) subtree = T...
'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 joining to), \'alias\' is the alias for the table we are joining to. If dupe_multis is True, any many-to-many or many-to-one joins will always creat...
def setup_joins(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True):
joins = [alias] last = [0] dupe_set = set() exclusions = set() extra_filters = [] int_alias = None for (pos, name) in enumerate(names): if (int_alias is not None): exclusions.add(int_alias) exclusions.add(alias) last.append(len(joins)) if (name == ...
'Sometimes joins at the end of a multi-table sequence can be trimmed. If the final join is against the same column as we are comparing against, and is an inner join, we can go back one step in a join chain and compare against the LHS of the join instead (and then repeat the optimization). The result, potentially, invol...
def trim_joins(self, target, join_list, last, trim, nonnull_check=False):
final = len(join_list) penultimate = last.pop() if (penultimate == final): penultimate = last.pop() if (trim and (final > 1)): extra = join_list[penultimate:] join_list = join_list[:penultimate] final = penultimate penultimate = last.pop() col = self.alias...
'For a column that is one of multiple pointing to the same table, update the internal data structures to note that this alias shouldn\'t be used for those other columns.'
def update_dupe_avoidance(self, opts, col, alias):
ident = id(opts) for name in opts.duplicate_targets[col]: try: self.dupe_avoidance[(ident, name)].add(alias) except KeyError: self.dupe_avoidance[(ident, name)] = set([alias])
'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.'
def split_exclude(self, filter_expr, prefix, can_reuse):
query = Query(self.model) query.add_filter(filter_expr) query.bump_prefix() query.clear_ordering(True) query.set_start(prefix) (alias, col) = query.select[0] query.where.add((Constraint(alias, col, None), 'isnull', False), AND) self.add_filter((('%s__in' % prefix), query), negate=True, t...
'Adjusts the limits on the rows retrieved. We use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, they are converted to the appropriate offset and limit values. Any limits passed in here are applied relative to the existing constraints. So low is added to the curren...
def set_limits(self, low=None, high=None):
if (high is not None): if (self.high_mark is not None): self.high_mark = min(self.high_mark, (self.low_mark + high)) else: self.high_mark = (self.low_mark + high) if (low is not None): if (self.high_mark is not None): self.low_mark = min(self.high_mark...
'Clears any existing limits.'
def clear_limits(self):
(self.low_mark, self.high_mark) = (0, None)
'Returns True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results.'
def can_filter(self):
return ((not self.low_mark) and (self.high_mark is None))
'Removes all fields from SELECT clause.'
def clear_select_clause(self):
self.select = [] self.select_fields = [] self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_aggregate_mask(())
'Clears the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns.'
def clear_select_fields(self):
self.select = [] self.select_fields = []
'Adds and resolves the given fields to the query\'s "distinct on" clause.'
def add_distinct_fields(self, *field_names):
self.distinct_fields = field_names self.distinct = True
'Adds the given (model) fields to the select set. The field names are added in the order specified.'
def add_fields(self, field_names, allow_m2m=True):
alias = self.get_initial_alias() opts = self.get_meta() try: for name in field_names: (field, target, u2, joins, u3, u4) = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, False, allow_m2m, True) final_alias = joins[(-1)] col = target.column if (l...
'Adds items from the \'ordering\' sequence to the query\'s "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix (\'-\' or \'?\') -- or ordinals, corresponding to column positions in the \'select\' list. If \'ordering\' is empty, all ordering is cleared from the qu...
def add_ordering(self, *ordering):
errors = [] for item in ordering: if (not ORDER_PATTERN.match(item)): errors.append(item) if errors: raise FieldError(('Invalid order_by arguments: %s' % errors)) if ordering: self.order_by.extend(ordering) else: self.default_ordering = False
'Removes any ordering settings. If \'force_empty\' is True, there will be no ordering in the resulting query (not even the model\'s default).'
def clear_ordering(self, force_empty=False):
self.order_by = [] self.extra_order_by = () if force_empty: self.default_ordering = False
'Expands the GROUP BY clause required by the query. 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.'
def set_group_by(self):
self.group_by = [] for sel in self.select: self.group_by.append(sel)
'Converts the query to do count(...) or count(distinct(pk)) in order to get its size.'
def add_count_column(self):
if (not self.distinct): if (not self.select): count = self.aggregates_module.Count('*', is_summary=True) else: assert (len(self.select) == 1), ("Cannot add count col with multiple cols in 'select': %r" % self.select) count = self.aggrega...
'Sets up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True).'
def add_select_related(self, fields):
field_dict = {} for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict self.related_select_cols = [] self.related_select_fields = []
'Adds data to the various extra_* attributes for user-created additions to the query.'
def add_extra(self, select, select_params, where, params, tables, order_by):
if select: select_pairs = SortedDict() if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for (name, entry) in select.items(): entry = force_text(entry) entry_params = [] pos = entry.find('%s') ...
'Remove any fields from the deferred loading set.'
def clear_deferred_loading(self):
self.deferred_loading = (set(), True)
'Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. The new field names are added to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading).'...
def add_deferred_loading(self, field_names):
(existing, defer) = self.deferred_loading if defer: self.deferred_loading = (existing.union(field_names), True) else: self.deferred_loading = (existing.difference(field_names), False)
'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 there are field names already specified for deferred loading, those names are removed from the new field_names before st...
def add_immediate_loading(self, field_names):
(existing, defer) = self.deferred_loading field_names = set(field_names) if ('pk' in field_names): field_names.remove('pk') field_names.add(self.model._meta.pk.name) if defer: self.deferred_loading = (field_names.difference(existing), False) else: self.deferred_loadin...
'If any fields are marked to be deferred, returns a dictionary mapping models to a set of names in those fields that will be loaded. If a model is not in the returned dictionary, none of it\'s fields are deferred. If no fields are marked for deferral, returns an empty dictionary.'
def get_loaded_field_names(self):
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
'Callback used by get_deferred_field_names().'
def get_loaded_field_names_cb(self, target, model, fields):
target[model] = set([f.name for f in fields])
'Set the mask of aggregates that will actually be returned by the SELECT'
def set_aggregate_mask(self, names):
if (names is None): self.aggregate_select_mask = None else: self.aggregate_select_mask = set(names) self._aggregate_select_cache = None
'Set the mask of extra select items that will be returned by SELECT, we don\'t actually remove them from the Query since they might be used later'
def set_extra_mask(self, names):
if (names is None): self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None
'The SortedDict of aggregate columns that are not masked, and should be used in the SELECT clause. This result is cached for optimization purposes.'
def _aggregate_select(self):
if (self._aggregate_select_cache is not None): return self._aggregate_select_cache elif (self.aggregate_select_mask is not None): self._aggregate_select_cache = SortedDict([(k, v) for (k, v) in self.aggregates.items() if (k in self.aggregate_select_mask)]) return self._aggregate_select_c...
'Sets the table from which to start joining. The start position is specified by the related attribute from the base model. This will automatically set to the select column to be the column linked from the previous table. This method is primarily for internal use and the error checking isn\'t as friendly as add_filter()...
def set_start(self, start):
opts = self.model._meta alias = self.get_initial_alias() (field, col, opts, joins, last, extra) = self.setup_joins(start.split(LOOKUP_SEP), opts, alias, False) select_col = self.alias_map[joins[1]].lhs_join_col select_alias = alias for alias in joins: self.unref_alias(alias) for alia...
'A helper to check if the given field should be treated as nullable. 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.'
def is_nullable(self, field):
if (connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and field.empty_strings_allowed): return True else: return field.null
'Instantiate an SQL aggregate * col is a column reference describing the subject field of the aggregate. It can be an alias, or a tuple describing a table and column name. * source is the underlying field or aggregate definition for the column reference. If the aggregate is not an ordinal or computed type, this referen...
def __init__(self, col, source=None, is_summary=False, **extra):
self.col = col self.source = source self.is_summary = is_summary self.extra = extra tmp = self while (tmp and isinstance(tmp, Aggregate)): if getattr(tmp, 'is_ordinal', False): tmp = ordinal_aggregate_field elif getattr(tmp, 'is_computed', False): tmp = co...
'Return the aggregate, rendered as SQL.'
def as_sql(self, qn, connection):
if hasattr(self.col, 'as_sql'): field_name = self.col.as_sql(qn, connection) elif isinstance(self.col, (list, tuple)): field_name = '.'.join([qn(c) for c in self.col]) else: field_name = self.col params = {'function': self.sql_function, 'field': field_name} params.update(self...
'Set up and execute delete queries for all the objects in pk_list. More than one physical query may be executed if there are a lot of values in pk_list.'
def delete_batch(self, pk_list, using, field=None):
if (not field): field = self.model._meta.pk for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE): where = self.where_class() where.add((Constraint(None, field.column, field), 'in', pk_list[offset:(offset + GET_ITERATOR_CHUNK_SIZE)]), AND) self.do_query(self.model._meta.d...
'Delete the queryset in one SQL query (if possible). For simple queries this is done by copying the query.query.where to self.query, for complex queries by using subquery.'
def delete_qs(self, query, using):
innerq = query.query innerq.get_initial_alias() self.get_initial_alias() innerq_used_tables = [t for t in innerq.tables if innerq.alias_refcount[t]] if (((not innerq_used_tables) or (innerq_used_tables == self.tables)) and (not len(innerq.having))): self.where = innerq.where else: ...
'Runs on initialization and after cloning. Any attributes that would normally be set in __init__ should go in here, instead, so that they are also set up after a clone() call.'
def _setup_query(self):
self.values = [] self.related_ids = None if (not hasattr(self, 'related_updates')): self.related_updates = {}
'Convert a dictionary of field name to value mappings into an update query. This is the entry point for the public update() method on querysets.'
def add_update_values(self, values):
values_seq = [] for (name, val) in six.iteritems(values): (field, model, direct, m2m) = self.model._meta.get_field_by_name(name) if ((not direct) or m2m): raise FieldError(('Cannot update model field %r (only non-relations and foreign keys permitted).' %...
'Turn a sequence of (field, model, value) triples into an update query. Used by add_update_values() as well as the "fast" update path when saving models.'
def add_update_fields(self, values_seq):
values_seq = [((value[0], value[1], force_text(value[2])) if isinstance(value[2], Promise) else value) for value in values_seq] self.values.extend(values_seq)
'Adds (name, value) to an update query for an ancestor model. Updates are coalesced so that we only run one update query per ancestor.'
def add_related_update(self, model, field, value):
try: self.related_updates[model].append((field, None, value)) except KeyError: self.related_updates[model] = [(field, None, value)]
'Returns a list of query objects: one for each update required to an ancestor model. Each query will have the same filtering conditions as the current query but will only update a single table.'
def get_related_updates(self):
if (not self.related_updates): return [] result = [] for (model, values) in six.iteritems(self.related_updates): query = UpdateQuery(model) query.values = values if (self.related_ids is not None): query.add_filter(('pk__in', self.related_ids)) result.appen...
'Set up the insert query from the \'insert_values\' dictionary. The dictionary gives the model field names and their target values. If \'raw_values\' is True, the values in the \'insert_values\' dictionary are inserted directly into the query, rather than passed as SQL parameters. This provides a way to insert NULL and...
def insert_values(self, fields, objs, raw=False):
self.fields = fields for field in fields: for obj in objs: value = getattr(obj, field.attname) if isinstance(value, Promise): setattr(obj, field.attname, force_text(value)) self.objs = objs self.raw = raw
'Converts the query into a date extraction query.'
def add_date_select(self, field_name, lookup_type, order='ASC'):
try: result = self.setup_joins(field_name.split(LOOKUP_SEP), self.get_meta(), self.get_initial_alias(), False) except FieldError: raise FieldDoesNotExist(("%s has no field named '%s'" % (self.model._meta.object_name, field_name))) field = result[0] assert isinstance(field,...
'Does any necessary class setup immediately prior to producing SQL. This is for things that can\'t necessarily be done in __init__ because we might not have all the pieces in place at that time. # TODO: after the query has been executed, the altered state should be # cleaned. We are not using a clone() of the query her...
def pre_sql_setup(self):
if (not self.query.tables): self.query.join((None, self.query.model._meta.db_table, None, None)) if ((not self.query.select) and self.query.default_cols and (not self.query.included_inherited_models)): self.query.setup_inherited_models() if (self.query.select_related and (not self.query.rela...
'A wrapper around connection.ops.quote_name that doesn\'t quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL).'
def quote_name_unless_alias(self, name):
if (name in self.quote_cache): return self.quote_cache[name] if (((name in self.query.alias_map) and (name not in self.query.table_map)) or (name in self.query.extra_select)): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name...
'Creates the SQL for this query. Returns the SQL string and list of parameters. If \'with_limits\' is False, any limit/offset information is not included in the query.'
def as_sql(self, with_limits=True, with_col_aliases=False):
if (with_limits and (self.query.low_mark == self.query.high_mark)): return ('', ()) self.pre_sql_setup() self.refcounts_before = self.query.alias_refcount.copy() out_cols = self.get_columns(with_col_aliases) (ordering, ordering_group_by) = self.get_ordering() distinct_fields = self.get_d...
'Perform the same functionality as the as_sql() method, returning an SQL string and parameters. However, the alias prefixes are bumped beforehand (in a copy -- the current query isn\'t changed), and any ordering is removed if the query is unsliced. Used when nesting this query inside another.'
def as_nested_sql(self):
obj = self.query.clone() if ((obj.low_mark == 0) and (obj.high_mark is None)): obj.clear_ordering(True) obj.bump_prefix() return obj.get_compiler(connection=self.connection).as_sql()
'Returns the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If \'with_aliases\' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguity with ...
def get_columns(self, with_aliases=False):
qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = [('(%s) AS %s' % (col[0], qn2(alias))) for (alias, col) in six.iteritems(self.query.extra_select)] aliases = set(self.query.extra_select.keys()) if with_aliases: col_aliases = aliases.copy() else: ...
'Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL dire...
def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False):
result = [] if (opts is None): opts = self.query.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name aliases = set() only_load = self.deferred_to_columns() if start_alias: seen = {None: start_alias} for (field, model) in opts.get_fields_with...
'Returns a quoted list of fields to use in DISTINCT ON part of the query. Note that this method can alter the tables in the query, and thus it must be called before get_from_clause().'
def get_distinct(self):
qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = [] opts = self.query.model._meta for name in self.query.distinct_fields: parts = name.split(LOOKUP_SEP) (field, col, alias, _, _) = self._setup_joins(parts, opts, None) (col, alias) = self._final_...
'Returns a tuple containing a list representing the SQL elements in the "order by" clause, and the list of SQL elements that need to be added to the GROUP BY clause as a result of the ordering. Also sets the ordering_aliases attribute on this instance to a list of extra aliases needed in the select. Determining the ord...
def get_ordering(self):
if self.query.extra_order_by: ordering = self.query.extra_order_by elif (not self.query.default_ordering): ordering = self.query.order_by else: ordering = (self.query.order_by or self.query.model._meta.ordering or []) qn = self.quote_name_unless_alias qn2 = self.connection.op...
'Returns the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given \'name\' parameter. The \'name\' is of the form \'field1__field2__...__fieldN\'.'
def find_ordering_name(self, name, opts, alias=None, default_order='ASC', already_seen=None):
(name, order) = get_order_dir(name, default_order) pieces = name.split(LOOKUP_SEP) (field, col, alias, joins, opts) = self._setup_joins(pieces, opts, alias) if (field.rel and (len(joins) > 1) and opts.ordering): if (not already_seen): already_seen = set() join_tuple = tuple([...
'A helper method for get_ordering and get_distinct. This method will call query.setup_joins, handle refcounts and then promote the joins. Note that get_ordering and get_distinct must produce same target columns on same input, as the prefixes of get_ordering and get_distinct must match. Executing SQL where this is not t...
def _setup_joins(self, pieces, opts, alias):
if (not alias): alias = self.query.get_initial_alias() (field, target, opts, joins, _, _) = self.query.setup_joins(pieces, opts, alias, False) joins_to_promote = [j for j in joins if (self.query.alias_refcount[j] < 2)] alias = joins[(-1)] col = target.column if (not field.rel): s...
'A helper method for get_distinct and get_ordering. This method will trim extra not-needed joins from the tail of the join chain. This is very similar to what is done in trim_joins, but we will trim LEFT JOINS here. It would be a good idea to consolidate this method and query.trim_joins().'
def _final_join_removal(self, col, alias):
if alias: while 1: join = self.query.alias_map[alias] if (col != join.rhs_join_col): break self.query.unref_alias(alias) alias = join.lhs_alias col = join.lhs_join_col return (col, alias)
'Returns a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Sub-classes, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables...
def get_from_clause(self):
result = [] qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name first = True for alias in self.query.tables: if (not self.query.alias_refcount[alias]): continue try: (name, alias, join_type, lhs, lhs_col, col, nullable) = self.query.alias_ma...
'Returns a tuple representing the SQL elements in the "group by" clause.'
def get_grouping(self, ordering_group_by):
qn = self.quote_name_unless_alias (result, params) = ([], []) if (self.query.group_by is not None): select_cols = (self.query.select + self.query.related_select_cols) if ((len(self.query.model._meta.fields) == len(self.query.select)) and self.connection.features.allows_group_by_pk): ...
'Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model).'
def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1, used=None, requested=None, restricted=None, nullable=None, dupe_set=None, avoid_set=None):
if ((not restricted) and self.query.max_depth and (cur_depth > self.query.max_depth)): return if (not opts): opts = self.query.get_meta() root_alias = self.query.get_initial_alias() self.query.related_select_cols = [] self.query.related_select_fields = [] if (not used...
'Converts the self.deferred_loading data structure to mapping of table names to sets of column names which are to be loaded. Returns the dictionary.'
def deferred_to_columns(self):
columns = {} self.query.deferred_to_data(columns, self.query.deferred_to_columns_cb) return columns
'Returns an iterator over the results from executing this query.'
def results_iter(self):
resolve_columns = hasattr(self, 'resolve_columns') fields = None has_aggregate_select = bool(self.query.aggregate_select) if (self.query.select_for_update and transaction.is_managed(self.using)): transaction.set_dirty(self.using) for rows in self.execute_sql(MULTI): for row in rows: ...
'Run the query against the database and returns the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case...
def execute_sql(self, result_type=MULTI):
try: (sql, params) = self.as_sql() if (not sql): raise EmptyResultSet except EmptyResultSet: if (result_type == MULTI): return iter([]) else: return cursor = self.connection.cursor() cursor.execute(sql, params) if (not result_type):...
'Creates the SQL for this query. Returns the SQL string and list of parameters.'
def as_sql(self):
assert (len(self.query.tables) == 1), 'Can only delete from one table at a time.' qn = self.quote_name_unless_alias result = [('DELETE FROM %s' % qn(self.query.tables[0]))] (where, params) = self.query.where.as_sql(qn=qn, connection=self.connection) if where: re...
'Creates the SQL for this query. Returns the SQL string and list of parameters.'
def as_sql(self):
self.pre_sql_setup() if (not self.query.values): return ('', ()) table = self.query.tables[0] qn = self.quote_name_unless_alias result = [('UPDATE %s' % qn(table))] result.append('SET') (values, update_params) = ([], []) for (field, model, val) in self.query.values: if...
'Execute the specified update. Returns the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available.'
def execute_sql(self, result_type):
cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) rows = ((cursor and cursor.rowcount) or 0) is_empty = (cursor is None) del cursor for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty: ...
'If the update depends on results from other tables, we need to do some munging of the "where" conditions to match the format required for (portable) SQL updates. That is done here. Further, if we are going to be running multiple updates, we pull out the id values to update at this point so that they don\'t change as a...
def pre_sql_setup(self):
self.query.select_related = False self.query.clear_ordering(True) super(SQLUpdateCompiler, self).pre_sql_setup() count = self.query.count_active_tables() if ((not self.query.related_updates) and (count == 1)): return query = self.query.clone(klass=Query) query.bump_prefix() query...
'Creates the SQL for this query. Returns the SQL string and list of parameters.'
def as_sql(self, qn=None):
if (qn is None): qn = self.quote_name_unless_alias sql = ('SELECT %s FROM (%s) subquery' % (', '.join([aggregate.as_sql(qn, self.connection) for aggregate in self.query.aggregate_select.values()]), self.query.subquery)) params = self.query.sub_params return (sql, params)
'Returns an iterator over the results from executing this query.'
def results_iter(self):
resolve_columns = hasattr(self, 'resolve_columns') if resolve_columns: from django.db.models.fields import DateTimeField fields = [DateTimeField()] else: from django.db.backends.util import typecast_timestamp needs_string_cast = self.connection.features.needs_datetime_string_...
'Adds \'objs\' to the collection of objects to be deleted. If the call is the result of a cascade, \'source\' should be the model that caused it, and \'nullable\' should be set to True if the relation can be null. Returns a list of all objects that were not already collected.'
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
if (not objs): return [] new_objs = [] model = objs[0].__class__ instances = self.data.setdefault(model, set()) for obj in objs: if (obj not in instances): new_objs.append(obj) instances.update(new_objs) if ((source is not None) and (not nullable)): if rev...
'Schedules a batch delete. Every instance of \'model\' that is related to an instance of \'obj\' through \'field\' will be deleted.'
def add_batch(self, model, field, objs):
self.batches.setdefault(model, {}).setdefault(field, set()).update(objs)
'Schedules a field update. \'objs\' must be a homogenous iterable collection of model instances (e.g. a QuerySet).'
def add_field_update(self, field, value, objs):
if (not objs): return model = objs[0].__class__ self.field_updates.setdefault(model, {}).setdefault((field, value), set()).update(objs)
'Determines if the objects in the given queryset-like can be fast-deleted. This can be done if there are no cascades, no parents and no signal listeners for the object class. The \'from_field\' tells where we are coming from - we need this to determine if the objects are in fact to be deleted. Allows also skipping pare...
def can_fast_delete(self, objs, from_field=None):
if (from_field and (from_field.rel.on_delete is not CASCADE)): return False if (not (hasattr(objs, 'model') and hasattr(objs, '_raw_delete'))): return False model = objs.model if (signals.pre_delete.has_listeners(model) or signals.post_delete.has_listeners(model) or signals.m2m_changed.h...
'Adds \'objs\' to the collection of objects to be deleted as well as all parent instances. \'objs\' must be a homogenous iterable collection of model instances (e.g. a QuerySet). If \'collect_related\' is True, related objects will be handled by their respective on_delete handler. If the call is the result of a casca...
def collect(self, objs, source=None, nullable=False, collect_related=True, source_attr=None, reverse_dependency=False):
if self.can_fast_delete(objs): self.fast_deletes.append(objs) return new_objs = self.add(objs, source, nullable, reverse_dependency=reverse_dependency) if (not new_objs): return model = new_objs[0].__class__ concrete_model = model._meta.concrete_model for ptr in six.iterv...
'Gets a QuerySet of objects related to ``objs`` via the relation ``related``.'
def related_objects(self, related, objs):
return related.model._base_manager.using(self.using).filter(**{('%s__in' % related.field.name): objs})
'Returns field\'s value prepared for saving into a database.'
def get_prep_value(self, value):
if (value is None): return None return six.text_type(value)
'Returns field\'s value just before saving.'
def pre_save(self, model_instance, add):
file = super(FileField, self).pre_save(model_instance, add) if (file and (not file._committed)): file.save(file.name, file, save=False) return file
'Updates field\'s width and height fields, if defined. This method is hooked up to model\'s post_init signal to update dimensions after instantiating a model instance. However, dimensions won\'t be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object fro...
def update_dimension_fields(self, instance, force=False, *args, **kwargs):
has_dimension_fields = (self.width_field or self.height_field) if (not has_dimension_fields): return file = getattr(instance, self.attname) if ((not file) and (not force)): return dimension_fields_filled = (not ((self.width_field and (not getattr(instance, self.width_field))) or (sel...
'Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can\'t be converted. Returns the converted value. Subclasses should override this.'
def to_python(self, value):
return value
'Validates value and throws ValidationError. Subclasses should override this to provide validation logic.'
def validate(self, value, model_instance):
if (not self.editable): return if (self._choices and (value not in validators.EMPTY_VALUES)): for (option_key, option_value) in self.choices: if isinstance(option_value, (list, tuple)): for (optgroup_key, optgroup_value) in option_value: if (value ...
'Convert the value\'s type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised.'
def clean(self, value, model_instance):
value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value
'Returns the database column data type for this field, for the provided connection.'
def db_type(self, connection):
data = DictWrapper(self.__dict__, connection.ops.quote_name, u'qn_') try: return (connection.creation.data_types[self.get_internal_type()] % data) except KeyError: return None
'Returns field\'s value just before saving.'
def pre_save(self, model_instance, add):
return getattr(model_instance, self.attname)
'Perform preliminary non-db specific value checks and conversions.'
def get_prep_value(self, value):
return value
'Returns field\'s value prepared for interacting with the database backend. Used by the default implementations of ``get_db_prep_save``and `get_db_prep_lookup```'
def get_db_prep_value(self, value, connection, prepared=False):
if (not prepared): value = self.get_prep_value(value) return value
'Returns field\'s value prepared for saving into a database.'
def get_db_prep_save(self, value, connection):
return self.get_db_prep_value(value, connection=connection, prepared=False)
'Perform preliminary non-db specific lookup checks and conversions'
def get_prep_lookup(self, lookup_type, value):
if hasattr(value, u'prepare'): return value.prepare() if hasattr(value, u'_prepare'): return value._prepare() if (lookup_type in (u'regex', u'iregex', u'month', u'day', u'week_day', u'search', u'contains', u'icontains', u'iexact', u'startswith', u'istartswith', u'endswith', u'iendswith', u'i...
'Returns field\'s value prepared for database lookup.'
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
if (not prepared): value = self.get_prep_lookup(lookup_type, value) if hasattr(value, u'get_compiler'): value = value.get_compiler(connection=connection) if (hasattr(value, u'as_sql') or hasattr(value, u'_as_sql')): if hasattr(value, u'relabel_aliases'): return value ...
'Returns a boolean of whether this field has a default value.'
def has_default(self):
return (self.default is not NOT_PROVIDED)
'Returns the default value for this field.'
def get_default(self):
if self.has_default(): if callable(self.default): return self.default() return force_text(self.default, strings_only=True) if ((not self.empty_strings_allowed) or (self.null and (not connection.features.interprets_empty_strings_as_nulls))): return None return u''
'Returns choices with a default blank choices included, for use as SelectField choices for this field.'
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
first_choice = ((include_blank and blank_choice) or []) if self.choices: return (first_choice + list(self.choices)) rel_model = self.rel.to if hasattr(self.rel, u'get_related_field'): lst = [(getattr(x, self.rel.get_related_field().attname), smart_text(x)) for x in rel_model._default_man...
'Returns flattened choices with a default blank choice included.'
def get_flatchoices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
first_choice = ((include_blank and blank_choice) or []) return (first_choice + list(self.flatchoices))
'Returns a string value of this field from the passed obj. This is used by the serialization framework.'
def value_to_string(self, obj):
return smart_text(self._get_val_from_obj(obj))
'Flattened version of choices tuple.'
def _get_flatchoices(self):
flat = [] for (choice, value) in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat
'Returns a django.forms.Field instance for this database Field.'
def formfield(self, form_class=forms.CharField, **kwargs):
defaults = {u'required': (not self.blank), u'label': capfirst(self.verbose_name), u'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults[u'initial'] = self.default defaults[u'show_hidden_initial'] = True else: defaults[u'initi...
'Returns the value of this field in the given model instance.'
def value_from_object(self, obj):
return getattr(obj, self.attname)
'Displays the module, class and name of the field.'
def __repr__(self):
path = (u'%s.%s' % (self.__class__.__module__, self.__class__.__name__)) name = getattr(self, u'name', None) if (name is not None): return (u'<%s: %s>' % (path, name)) return (u'<%s>' % path)