desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns a list of (related-object, model) pairs. Similar to
get_fields_with_model().'
| def get_all_related_objects_with_model(self, local_only=False, include_hidden=False):
| try:
self._related_objects_cache
except AttributeError:
self._fill_related_objects_cache()
predicates = []
if local_only:
predicates.append((lambda k, v: (not v)))
if (not include_hidden):
predicates.append((lambda k, v: (not k.field.rel.is_hidden())))
return filt... |
'Returns a list of (related-m2m-object, model) pairs. Similar to
get_fields_with_model().'
| def get_all_related_m2m_objects_with_model(self):
| try:
cache = self._related_many_to_many_cache
except AttributeError:
cache = self._fill_related_many_to_many_cache()
return cache.items()
|
'Returns a list of parent classes leading to \'model\' (order from closet
to most distant ancestor). This has to handle the case were \'model\' is
a granparent or even more distant relation.'
| def get_base_chain(self, model):
| if (not self.parents):
return
if (model in self.parents):
return [model]
for parent in self.parents:
res = parent._meta.get_base_chain(model)
if res:
res.insert(0, parent)
return res
raise TypeError(('%r is not an ancestor of this... |
'Returns a list of all the ancestor of this model as a list. Useful for
determining if something is an ancestor, regardless of lineage.'
| def get_parent_list(self):
| result = set()
for parent in self.parents:
result.add(parent)
result.update(parent._meta.get_parent_list())
return result
|
'Returns the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Returns None if the model isn\'t an ancestor of this one.'
| def get_ancestor_link(self, ancestor):
| if (ancestor in self.parents):
return self.parents[ancestor]
for parent in self.parents:
parent_link = parent._meta.get_ancestor_link(ancestor)
if parent_link:
return (self.parents[parent] or parent_link)
|
'Returns a list of Options objects that are ordered with respect to this object.'
| def get_ordered_objects(self):
| if (not hasattr(self, '_ordered_objects')):
objects = []
self._ordered_objects = objects
return self._ordered_objects
|
'Returns the index of the primary key field in the self.fields list.'
| def pk_index(self):
| return self.fields.index(self.pk)
|
'Returns choices with a default blank choices included, for use
as SelectField choices for this field.
Analogue of django.db.models.fields.Field.get_choices, provided
initially for utilisation by RelatedFilterSpec.'
| def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_to_currently_related=False):
| first_choice = ((include_blank and blank_choice) or [])
queryset = self.model._default_manager.all()
if limit_to_currently_related:
queryset = queryset.complex_filter({('%s__isnull' % self.parent_model._meta.module_name): False})
lst = [(x._get_pk_val(), smart_unicode(x)) for x in queryset]
... |
'Get the fields in this class that should be edited inline.'
| def editable_fields(self):
| return [f for f in (self.opts.fields + self.opts.many_to_many) if (f.editable and (f != self.field))]
|
'Fill in all the cache information. This method is threadsafe, in the
sense that every caller will see the same state upon return, and if the
cache is already initialised, it does no work.'
| def _populate(self):
| if self.loaded:
return
self.write_lock.acquire()
try:
if self.loaded:
return
for app_name in settings.INSTALLED_APPS:
if (app_name in self.handled):
continue
self.load_app(app_name, True)
if (not self.nesting_level):
... |
'Loads the app with the provided fully qualified name, and returns the
model module.'
| def load_app(self, app_name, can_postpone=False):
| self.handled[app_name] = None
self.nesting_level += 1
app_module = import_module(app_name)
try:
models = import_module('.models', app_name)
except ImportError:
self.nesting_level -= 1
if (not module_has_submodule(app_module, 'models')):
return None
elif ca... |
'Returns true if the model cache is fully populated.
Useful for code that wants to cache the results of get_models() for
themselves once it is safe to do so.'
| def app_cache_ready(self):
| return self.loaded
|
'Returns a list of all installed modules that contain models.'
| def get_apps(self):
| self._populate()
apps = [(v, k) for (k, v) in self.app_store.items()]
apps.sort()
return [elt[1] for elt in apps]
|
'Returns the module containing the models for the given app_label. If
the app has no models in it and \'emptyOK\' is True, returns None.'
| def get_app(self, app_label, emptyOK=False):
| self._populate()
self.write_lock.acquire()
try:
for app_name in settings.INSTALLED_APPS:
if (app_label == app_name.split('.')[(-1)]):
mod = self.load_app(app_name, False)
if (mod is None):
if emptyOK:
return None... |
'Returns the map of known problems with the INSTALLED_APPS.'
| def get_app_errors(self):
| self._populate()
return self.app_errors
|
'Given a module containing models, returns a list of the models.
Otherwise returns a list of all installed models.
By default, auto-created models (i.e., m2m models without an
explicit intermediate table) are not included. However, if you
specify include_auto_created=True, they will be.
By default, models created to sa... | def get_models(self, app_mod=None, include_auto_created=False, include_deferred=False):
| cache_key = (app_mod, include_auto_created, include_deferred)
try:
return self._get_models_cache[cache_key]
except KeyError:
pass
self._populate()
if app_mod:
app_list = [self.app_models.get(app_mod.__name__.split('.')[(-2)], SortedDict())]
else:
app_list = self.a... |
'Returns the model matching the given app_label and case-insensitive
model_name.
Returns None if no model is found.'
| def get_model(self, app_label, model_name, seed_cache=True):
| if seed_cache:
self._populate()
return self.app_models.get(app_label, SortedDict()).get(model_name.lower())
|
'Register a set of models as belonging to an app.'
| def register_models(self, app_label, *models):
| for model in models:
model_name = model._meta.object_name.lower()
model_dict = self.app_models.setdefault(app_label, SortedDict())
if (model_name in model_dict):
fname1 = os.path.abspath(sys.modules[model.__module__].__file__)
fname2 = os.path.abspath(sys.modules[mode... |
'Add a node to the where-tree. If the data is a list or tuple, it is
expected to be of the form (obj, lookup_type, value), where obj is
a Constraint object, and is then slightly munged before being stored
(to avoid storing any reference to field objects). Otherwise, the \'data\'
is stored unchanged and can be any class... | def add(self, data, connector):
| if (not isinstance(data, (list, tuple))):
super(WhereNode, self).add(data, connector)
return
(obj, lookup_type, value) = data
if (hasattr(value, '__iter__') and hasattr(value, 'next')):
value = list(value)
if isinstance(value, datetime.datetime):
annotation = datetime.dat... |
'Returns the SQL version of the where clause and the value to be
substituted in. Returns None, None if this node is empty.
If \'node\' is provided, that is the root of the SQL generation
(generally not needed except by the internal implementation for
recursion).'
| def as_sql(self, qn, connection):
| if (not self.children):
return (None, [])
result = []
result_params = []
empty = True
for child in self.children:
try:
if hasattr(child, 'as_sql'):
(sql, params) = child.as_sql(qn=qn, connection=connection)
else:
(sql, params) =... |
'Turn a tuple (table_alias, column_name, db_type, lookup_type,
value_annot, params) into valid SQL.
Returns the string for the SQL fragment and the parameters to use for
it.'
| def make_atom(self, child, qn, connection):
| (lvalue, lookup_type, value_annot, params_or_value) = child
if hasattr(lvalue, 'process'):
try:
(lvalue, params) = lvalue.process(lookup_type, params_or_value, connection)
except EmptyShortCircuit:
raise EmptyResultSet
else:
params = Field().get_db_prep_lookup... |
'Returns the SQL fragment used for the left-hand side of a column
constraint (for example, the "T1.foo" portion in the clause
"WHERE ... T1.foo = 6").'
| def sql_for_columns(self, data, qn, connection):
| (table_alias, name, db_type) = data
if table_alias:
lhs = ('%s.%s' % (qn(table_alias), qn(name)))
else:
lhs = qn(name)
return (connection.ops.field_cast_sql(db_type) % lhs)
|
'Relabels the alias values of any children. \'change_map\' is a dictionary
mapping old (current) alias values to the new values.'
| def relabel_aliases(self, change_map, node=None):
| if (not node):
node = self
for (pos, child) in enumerate(node.children):
if hasattr(child, 'relabel_aliases'):
child.relabel_aliases(change_map)
elif isinstance(child, tree.Node):
self.relabel_aliases(change_map, child)
elif isinstance(child, (list, tuple)... |
'Save the state of the Constraint for pickling.
Fields aren\'t necessarily pickleable, because they can have
callable default values. So, instead of pickling the field
store a reference so we can restore it manually'
| def __getstate__(self):
| obj_dict = self.__dict__.copy()
if self.field:
obj_dict['model'] = self.field.model
obj_dict['field_name'] = self.field.name
del obj_dict['field']
return obj_dict
|
'Restore the constraint'
| def __setstate__(self, data):
| model = data.pop('model', None)
field_name = data.pop('field_name', None)
self.__dict__.update(data)
if (model is not None):
self.field = model._meta.get_field(field_name)
else:
self.field = None
|
'Returns a tuple of data suitable for inclusion in a WhereNode
instance.'
| def process(self, lookup_type, value, connection):
| from django.db.models.base import ObjectDoesNotExist
try:
if self.field:
params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection, prepared=True)
db_type = self.field.db_type(connection=connection)
else:
params = Field().get_db_prep_loo... |
'Convert the database-returned value into a type that is consistent
across database backends.
By default, this defers to the underlying backend operations, but
it can be overridden by Query classes for specific backends.'
| def convert_values(self, value, field, connection):
| return connection.ops.convert_values(value, field)
|
'Returns the query as a string of SQL with the parameter values
substituted in.
Parameter values won\'t necessarily be quoted correctly, since that is
done by the database interface at execution time.'
| def __str__(self):
| (sql, params) = self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
return (sql % params)
|
'Pickling support.'
| def __getstate__(self):
| obj_dict = self.__dict__.copy()
obj_dict['related_select_fields'] = []
obj_dict['related_select_cols'] = []
obj_dict['select_fields'] = [(((f is not None) and f.name) or None) for f in obj_dict['select_fields']]
return obj_dict
|
'Unpickling support.'
| def __setstate__(self, obj_dict):
| opts = obj_dict['model']._meta
obj_dict['select_fields'] = [(((name is not None) and opts.get_field(name)) or None) for name in obj_dict['select_fields']]
self.__dict__.update(obj_dict)
|
'Returns the Options instance (the model._meta) from which to start
processing. Normally, this is self.model._meta, but it can be changed
by subclasses.'
| def get_meta(self):
| return self.model._meta
|
'Creates a copy of the current instance. The \'kwargs\' parameter can be
used by clients to update attributes after copying has taken place.'
| def clone(self, klass=None, memo=None, **kwargs):
| obj = Empty()
obj.__class__ = (klass or self.__class__)
obj.model = self.model
obj.alias_refcount = self.alias_refcount.copy()
obj.alias_map = self.alias_map.copy()
obj.table_map = self.table_map.copy()
obj.join_map = self.join_map.copy()
obj.rev_join_map = self.rev_join_map.copy()
o... |
'Convert the database-returned value into a type that is consistent
across database backends.
By default, this defers to the underlying backend operations, but
it can be overridden by Query classes for specific backends.'
| def convert_values(self, value, field, connection):
| return connection.ops.convert_values(value, field)
|
'Resolve the value of aggregates returned by the database to
consistent (and reasonable) types.
This is required because of the predisposition of certain backends
to return Decimal and long types when they are not needed.'
| def resolve_aggregate(self, value, aggregate, connection):
| if (value is None):
if aggregate.is_ordinal:
return 0
return value
elif aggregate.is_ordinal:
return int(value)
elif aggregate.is_computed:
return float(value)
else:
return self.convert_values(value, aggregate.field, connection)
|
'Returns the dictionary with the values of the existing aggregations.'
| def get_aggregation(self, using):
| if (not self.aggregate_select):
return {}
if (self.group_by is not None):
from django.db.models.sql.subqueries import AggregateQuery
query = AggregateQuery(self.model)
obj = self.clone()
for (alias, aggregate) in self.aggregate_select.items():
if aggregate.is_... |
'Performs a COUNT() query using the current filter constraints.'
| def get_count(self, using):
| obj = self.clone()
if ((len(self.select) > 1) or self.aggregate_select):
from django.db.models.sql.subqueries import AggregateQuery
subquery = obj
subquery.clear_ordering(True)
subquery.clear_limits()
obj = AggregateQuery(obj.model)
try:
obj.add_subque... |
'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.'
| def combine(self, rhs, connector):
| assert (self.model == rhs.model), 'Cannot combine queries on two different base models.'
assert self.can_filter(), 'Cannot combine queries once a slice has been taken.'
assert (self.distinct == rhs.distinct), 'Cannot combine a unique query with ... |
'Converts the self.deferred_loading data structure to an alternate data
structure, describing the field that *will* be loaded. This is used to
compute the columns to select from the database and also by the
QuerySet class to work out which fields are being initialised on each
model. Models that have all their fields in... | def deferred_to_data(self, target, callback):
| (field_names, defer) = self.deferred_loading
if (not field_names):
return
columns = set()
orig_opts = self.model._meta
seen = {}
must_include = {self.model: set([orig_opts.pk])}
for field_name in field_names:
parts = field_name.split(LOOKUP_SEP)
cur_model = self.model... |
'Callback used by deferred_to_columns(). The "target" parameter should
be a set instance.'
| def deferred_to_columns_cb(self, target, model, fields):
| table = model._meta.db_table
if (table not in target):
target[table] = set()
for field in fields:
target[table].add(field.column)
|
'Returns a table alias for the given table_name and whether this is a
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.'
| def table_alias(self, table_name, create=False):
| current = self.table_map.get(table_name)
if ((not create) and current):
alias = current[0]
self.alias_refcount[alias] += 1
return (alias, False)
if current:
alias = ('%s%d' % (self.alias_prefix, (len(self.alias_map) + 1)))
current.append(alias)
else:
alias... |
'Increases the reference count for this alias.'
| def ref_alias(self, alias):
| self.alias_refcount[alias] += 1
|
'Decreases the reference count for this alias.'
| def unref_alias(self, alias):
| self.alias_refcount[alias] -= 1
|
'Promotes the join type of an alias to an outer join if it\'s possible
for the join to contain NULL values on the left. If \'unconditional\' is
False, the join is only promoted if it is nullable, otherwise it is
always promoted.
Returns True if the join was promoted by this call.'
| def promote_alias(self, alias, unconditional=False):
| if ((unconditional or self.alias_map[alias][NULLABLE]) and (self.alias_map[alias][JOIN_TYPE] != self.LOUTER)):
data = list(self.alias_map[alias])
data[JOIN_TYPE] = self.LOUTER
self.alias_map[alias] = tuple(data)
return True
return False
|
'Walks along a chain of aliases, promoting the first nullable join and
any joins following that. If \'must_promote\' is True, all the aliases in
the chain are promoted.'
| def promote_alias_chain(self, chain, must_promote=False):
| for alias in chain:
if self.promote_alias(alias, must_promote):
must_promote = True
|
'Given a "before" copy of the alias_refcounts dictionary (as
\'initial_refcounts\') and a collection of aliases that may have been
changed or created, works out which aliases have been created since
then and which ones haven\'t been used and promotes all of those
aliases, plus any children of theirs in the alias tree, ... | def promote_unused_aliases(self, initial_refcounts, used_aliases):
| considered = {}
for alias in self.tables:
if (alias not in used_aliases):
continue
if ((alias not in initial_refcounts) or (self.alias_refcount[alias] == initial_refcounts[alias])):
parent = self.alias_map[alias][LHS_ALIAS]
must_promote = considered.get(parent... |
'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 = {}
for (pos, alias) in enumerate(self.tables):
if (alias in exceptions):
continue
new_alias = ('%s%d' % (prefix, pos))
change_map[a... |
'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.'
| def count_active_tables(self):
| return len([1 for count in self.alias_refcount.itervalues() 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
root_alias = self.tables[0]
seen = {None: root_alias}
proxied_model = get_proxied_model(opts)
for (field, model) in opts.get_fields_with_model():
if (model not in seen):
if (model is proxied_model):
seen[model] = root_alias
else... |
'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))
if ((len(parts) == 1) or (parts[(-1)] not in self.query_terms)):
lookup_type = 'exact'
else:
lookup_type = parts.pop()
having_cla... |
'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):
| final = len(join_list)
penultimate = last.pop()
if (penultimate == final):
penultimate = last.pop()
if (trim and (len(join_list) > 1)):
extra = join_list[penultimate:]
join_list = join_list[:penultimate]
final = penultimate
penultimate = last.pop()
col = s... |
'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, can_reuse=can_reuse)
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), q... |
'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))
|
'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 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_unicode(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
if defer:
self.deferred_loading = (set(field_names).difference(existing), False)
else:
self.deferred_loading = (set(field_names), False)
|
'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):
| collection = {}
self.deferred_to_data(collection, self.get_loaded_field_names_cb)
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 ali... |
'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... |
'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 values.iteritems():
(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).' % fi... |
'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):
| 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 self.related_updates.iteritems():
query = UpdateQuery(model)
query.values = values
if (self.related_ids is not None):
query.add_filter(('pk__in', self.related_ids))
result.append(q... |
'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, insert_values, raw_values=False):
| (placeholders, values) = ([], [])
for (field, val) in insert_values:
placeholders.append((field, val))
self.columns.append(field.column)
values.append(val)
if raw_values:
self.values.extend([(None, v) for v in values])
else:
self.params += tuple(values)
se... |
'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.'
| 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()
out_cols = self.get_columns(with_col_aliases)
(ordering, ordering_group_by) = self.get_ordering()
(from_, f_params) = self.get_from_clause()
qn = self.quote_name_unless_alias
(whe... |
'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 self.query.extra_select.iteritems()]
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()
proxied_model = get_proxied_model(opts)
if start_alias:
seen = {None: start_alias}
... |
'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)
qn = self.quote_name_unless_alias
qn2 = self.connection.ops.quot... |
'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)
if (not alias):
alias = self.query.get_initial_alias()
(field, target, opts, joins, last, extra) = self.query.setup_joins(pieces, opts, alias, False)
alias = joins[(-1)]
col = target.column
if (not fie... |
'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):
| qn = self.quote_name_unless_alias
(result, params) = ([], [])
if (self.query.group_by is not None):
if ((len(self.query.model._meta.fields) == len(self.query.select)) and self.connection.features.allows_group_by_pk):
self.query.group_by = [(self.query.model._meta.db_table, self.query.mod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.