desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Calculate the reference key for this reference
Currently this is a two-tuple of the id()\'s of the
target object and the target function respectively.'
| def calculateKey(cls, target):
| return (id(target.im_self), id(target.im_func))
|
'Give a friendly representation of the object'
| def __str__(self):
| return ('%s( %s.%s )' % (self.__class__.__name__, self.selfName, self.funcName))
|
'Whether we are still a valid reference'
| def __nonzero__(self):
| return (self() is not None)
|
'Compare with another reference'
| def __cmp__(self, other):
| if (not isinstance(other, self.__class__)):
return cmp(self.__class__, type(other))
return cmp(self.key, other.key)
|
'Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.'
| def __call__(self):
| target = self.weakSelf()
if (target is not None):
function = self.weakFunc()
if (function is not None):
return function.__get__(target)
return None
|
'Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be cal... | def __init__(self, target, onDelete=None):
| assert (getattr(target.im_self, target.__name__) == target), ("method %s isn't available as the attribute %s of %s" % (target, target.__name__, target.im_self))
super(BoundNonDescriptorMethodWeakref, self).__init__(target, onDelete)
|
'Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.'
| def __call__(self):
| target = self.weakSelf()
if (target is not None):
function = self.weakFunc()
if (function is not None):
return getattr(target, function.__name__)
return None
|
'Create a new signal.
providing_args
A list of the arguments this signal can pass along in a send() call.'
| def __init__(self, providing_args=None):
| self.receivers = []
if (providing_args is None):
providing_args = []
self.providing_args = set(providing_args)
self.lock = threading.Lock()
|
'Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
If weak is True, then receiver must be weak-referencable (more
precisely saferef.safeRef() must be able to create a reference
to the receiver).
Receivers must be ... | def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
| from django.conf import settings
if settings.DEBUG:
import inspect
assert callable(receiver), 'Signal receivers must be callable.'
try:
argspec = inspect.getargspec(receiver)
except TypeError:
try:
argspec = inspect.getargspec(r... |
'Disconnect receiver from sender for signal.
If weak references are used, disconnect need not be called. The receiver
will be remove from dispatch automatically.
Arguments:
receiver
The registered receiver to disconnect. May be none if
dispatch_uid is specified.
sender
The registered sender to disconnect
weak
The weakr... | def disconnect(self, receiver=None, sender=None, weak=True, dispatch_uid=None):
| if dispatch_uid:
lookup_key = (dispatch_uid, _make_id(sender))
else:
lookup_key = (_make_id(receiver), _make_id(sender))
self.lock.acquire()
try:
for index in xrange(len(self.receivers)):
(r_key, _) = self.receivers[index]
if (r_key == lookup_key):
... |
'Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop, so it is quite possible to not have all
receivers called if a raises an error.
Arguments:
sender
The sender of the signal Either a specific object or None.
named
N... | def send(self, sender, **named):
| responses = []
if (not self.receivers):
return responses
for receiver in self._live_receivers(_make_id(sender)):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses
|
'Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers. These
arguments must be a subset of the arg... | def send_robust(self, sender, **named):
| responses = []
if (not self.receivers):
return responses
for receiver in self._live_receivers(_make_id(sender)):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception as err:
responses.append((receiver, err))
else:
... |
'Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.'
| def _live_receivers(self, senderkey):
| none_senderkey = _make_id(None)
receivers = []
for ((receiverkey, r_senderkey), receiver) in self.receivers:
if ((r_senderkey == none_senderkey) or (r_senderkey == senderkey)):
if isinstance(receiver, WEAKREF_TYPES):
receiver = receiver()
if (receiver is n... |
'Remove dead receivers from connections.'
| def _remove_receiver(self, receiver):
| self.lock.acquire()
try:
to_remove = []
for (key, connected_receiver) in self.receivers:
if (connected_receiver == receiver):
to_remove.append(key)
for key in to_remove:
last_idx = (len(self.receivers) - 1)
for (idx, (r_key, _)) in enum... |
'Creates some methods once self._meta has been populated.'
| def _prepare(cls):
| opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False)
def make_foreign_order_accessors(field, model, cls):... |
'Provide pickling support. Normally, this just dispatches to Python\'s
standard handling. However, for models with deferred field loading, we
need to do things manually, as they\'re dynamically created classes and
only module-level classes can be pickled by the default path.'
| def __reduce__(self):
| data = self.__dict__
model = self.__class__
defers = []
pk_val = None
if self._deferred:
from django.db.models.query_utils import deferred_class_factory
factory = deferred_class_factory
for field in self._meta.fields:
if isinstance(self.__class__.__dict__.get(fiel... |
'Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there\'s
no Field object with this name on the model, the model attribute\'s
value is returned directly.
Used to serialize a field\'s value (in the serializer, or form output,
for examp... | def serializable_value(self, field_name):
| try:
field = self._meta.get_field_by_name(field_name)[0]
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
|
'Saves the current instance. Override this in a subclass if you want to
control the saving process.
The \'force_insert\' and \'force_update\' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.'
| def save(self, force_insert=False, force_update=False, using=None):
| if (force_insert and force_update):
raise ValueError('Cannot force both insert and updating in model saving.')
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
|
'Does the heavy-lifting involved in saving. Subclasses shouldn\'t need to
override this method. It\'s separate from save() in order to hide the
need for overrides of save() to pass around internal-only parameters
(\'raw\', \'cls\', and \'origin\').'
| def save_base(self, raw=False, cls=None, origin=None, force_insert=False, force_update=False, using=None):
| using = (using or router.db_for_write(self.__class__, instance=self))
connection = connections[using]
assert (not (force_insert and force_update))
if (cls is None):
cls = self.__class__
meta = cls._meta
if (not meta.proxy):
origin = cls
else:
meta = cls._m... |
'Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.'
| def clean(self):
| pass
|
'Checks unique constraints on the model and raises ``ValidationError``
if any failed.'
| def validate_unique(self, exclude=None):
| (unique_checks, date_checks) = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for (k, v) in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(erro... |
'Gather a list of checks to perform. Since validate_unique could be
called from a ModelForm, some fields may have been excluded; we can\'t
perform a unique check on a model that is missing fields involved
in that check.
Fields that did not validate should also be excluded, but they need
to be passed in via the exclude ... | def _get_unique_checks(self, exclude=None):
| if (exclude is None):
exclude = []
unique_checks = []
unique_togethers = [(self.__class__, self._meta.unique_together)]
for parent_class in self._meta.parents.keys():
if parent_class._meta.unique_together:
unique_togethers.append((parent_class, parent_class._meta.unique_toget... |
'Calls clean_fields, clean, and validate_unique, on the model,
and raises a ``ValidationError`` for any errors that occured.'
| def full_clean(self, exclude=None):
| errors = {}
if (exclude is None):
exclude = []
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
for name in err... |
'Cleans all fields and raises a ValidationError containing message_dict
of all validation errors if any occur.'
| def clean_fields(self, exclude=None):
| if (exclude is None):
exclude = []
errors = {}
for f in self._meta.fields:
if (f.name in exclude):
continue
raw_value = getattr(self, f.attname)
if (f.blank and (raw_value in validators.EMPTY_VALUES)):
continue
try:
setattr(self, f.... |
'Deep copy of a QuerySet doesn\'t populate the cache'
| def __deepcopy__(self, memo):
| obj = self.__class__()
for (k, v) in self.__dict__.items():
if (k in ('_iter', '_result_cache')):
obj.__dict__[k] = None
else:
obj.__dict__[k] = deepcopy(v, memo)
return obj
|
'Allows the QuerySet to be pickled.'
| def __getstate__(self):
| len(self)
obj_dict = self.__dict__.copy()
obj_dict['_iter'] = None
return obj_dict
|
'Retrieves an item or slice from the set of results.'
| def __getitem__(self, k):
| if (not isinstance(k, (slice, int, long))):
raise TypeError
assert (((not isinstance(k, slice)) and (k >= 0)) or (isinstance(k, slice) and ((k.start is None) or (k.start >= 0)) and ((k.stop is None) or (k.stop >= 0)))), 'Negative indexing is not supported.'
if (self._result_cache is not ... |
'An iterator over the results from applying this QuerySet to the
database.'
| def iterator(self):
| fill_cache = self.query.select_related
if isinstance(fill_cache, dict):
requested = fill_cache
else:
requested = None
max_depth = self.query.max_depth
extra_select = self.query.extra_select.keys()
aggregate_select = self.query.aggregate_select.keys()
only_load = self.query.ge... |
'Returns a dictionary containing the calculations (aggregation)
over the current queryset
If args is present the expression is passed as a kwarg using
the Aggregate object\'s default alias.'
| def aggregate(self, *args, **kwargs):
| for arg in args:
kwargs[arg.default_alias] = arg
query = self.query.clone()
for (alias, aggregate_expr) in kwargs.items():
query.add_aggregate(aggregate_expr, self.model, alias, is_summary=True)
return query.get_aggregation(using=self.db)
|
'Performs a SELECT COUNT() and returns the number of records as an
integer.
If the QuerySet is already fully cached this simply returns the length
of the cached results set to avoid multiple SELECT COUNT(*) calls.'
| def count(self):
| if ((self._result_cache is not None) and (not self._iter)):
return len(self._result_cache)
return self.query.get_count(using=self.db)
|
'Performs the query and returns a single object matching the given
keyword arguments.'
| def get(self, *args, **kwargs):
| clone = self.filter(*args, **kwargs)
if self.query.can_filter():
clone = clone.order_by()
num = len(clone)
if (num == 1):
return clone._result_cache[0]
if (not num):
raise self.model.DoesNotExist(('%s matching query does not exist.' % self.model._meta.object_na... |
'Creates a new object with the given kwargs, saving it to the database
and returning the created object.'
| def create(self, **kwargs):
| obj = self.model(**kwargs)
self._for_write = True
obj.save(force_insert=True, using=self.db)
return obj
|
'Looks up an object with the given kwargs, creating one if necessary.
Returns a tuple of (object, created), where created is a boolean
specifying whether an object was created.'
| def get_or_create(self, **kwargs):
| assert kwargs, 'get_or_create() must be passed at least one keyword argument'
defaults = kwargs.pop('defaults', {})
lookup = kwargs.copy()
for f in self.model._meta.fields:
if (f.attname in lookup):
lookup[f.name] = lookup.pop(f.attname)
try:
self.... |
'Returns the latest object, according to the model\'s \'get_latest_by\'
option or optional given field_name.'
| def latest(self, field_name=None):
| latest_by = (field_name or self.model._meta.get_latest_by)
assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model"
assert self.query.can_filter(), 'Cannot change a query once a slice has been taken.'
... |
'Returns a dictionary mapping each of the given IDs to the object with
that ID.'
| def in_bulk(self, id_list):
| assert self.query.can_filter(), "Cannot use 'limit' or 'offset' with in_bulk"
assert isinstance(id_list, (tuple, list, set, frozenset)), 'in_bulk() must be provided with a list of IDs.'
if (not id_list):
return {}
qs = self._clone()
qs.query.add_filt... |
'Deletes the records in the current QuerySet.'
| def delete(self):
| assert self.query.can_filter(), "Cannot use 'limit' or 'offset' with delete."
del_query = self._clone()
del_query._for_write = True
del_query.query.select_related = False
del_query.query.clear_ordering()
collector = Collector(using=del_query.db)
collector.collect(del_query)... |
'Updates all elements in the current QuerySet, setting all the given
fields to the appropriate values.'
| def update(self, **kwargs):
| assert self.query.can_filter(), 'Cannot update a query once a slice has been taken.'
self._for_write = True
query = self.query.clone(sql.UpdateQuery)
query.add_update_values(kwargs)
if (not transaction.is_managed(using=self.db)):
transaction.enter_transaction_manag... |
'A version of update that accepts field objects instead of field names.
Used primarily for model saving and not intended for use by general
code (it requires too much poking around at model internals to be
useful at that level).'
| def _update(self, values):
| assert self.query.can_filter(), 'Cannot update a query once a slice has been taken.'
query = self.query.clone(sql.UpdateQuery)
query.add_update_fields(values)
self._result_cache = None
return query.get_compiler(self.db).execute_sql(None)
|
'Returns a list of datetime objects representing all available dates for
the given field_name, scoped to \'kind\'.'
| def dates(self, field_name, kind, order='ASC'):
| assert (kind in ('month', 'year', 'day')), "'kind' must be one of 'year', 'month' or 'day'."
assert (order in ('ASC', 'DESC')), "'order' must be either 'ASC' or 'DESC'."
return self._clone(klass=DateQuerySet, setup=True, _field_name=field_name, _kind=kind, _order=or... |
'Returns an empty QuerySet.'
| def none(self):
| return self._clone(klass=EmptyQuerySet)
|
'Returns a new QuerySet that is a copy of the current one. This allows a
QuerySet to proxy for a model manager in some cases.'
| def all(self):
| return self._clone()
|
'Returns a new QuerySet instance with the args ANDed to the existing
set.'
| def filter(self, *args, **kwargs):
| return self._filter_or_exclude(False, *args, **kwargs)
|
'Returns a new QuerySet instance with NOT (args) ANDed to the existing
set.'
| def exclude(self, *args, **kwargs):
| return self._filter_or_exclude(True, *args, **kwargs)
|
'Returns a new QuerySet instance with filter_obj added to the filters.
filter_obj can be a Q object (or anything with an add_to_query()
method) or a dictionary of keyword lookup arguments.
This exists to support framework features such as \'limit_choices_to\',
and usually it will be more natural to use other methods.'
| def complex_filter(self, filter_obj):
| if (isinstance(filter_obj, Q) or hasattr(filter_obj, 'add_to_query')):
clone = self._clone()
clone.query.add_q(filter_obj)
return clone
else:
return self._filter_or_exclude(None, **filter_obj)
|
'Returns a new QuerySet instance that will select related objects.
If fields are specified, they must be ForeignKey fields and only those
related objects are included in the selection.'
| def select_related(self, *fields, **kwargs):
| depth = kwargs.pop('depth', 0)
if kwargs:
raise TypeError(('Unexpected keyword arguments to select_related: %s' % (kwargs.keys(),)))
obj = self._clone()
if fields:
if depth:
raise TypeError('Cannot pass both "depth" and fields to select_rel... |
'Copies the related selection status from the QuerySet \'other\' to the
current QuerySet.'
| def dup_select_related(self, other):
| self.query.select_related = other.query.select_related
|
'Return a query set in which the returned objects have been annotated
with data aggregated from related fields.'
| def annotate(self, *args, **kwargs):
| for arg in args:
if (arg.default_alias in kwargs):
raise ValueError(("The named annotation '%s' conflicts with the default name for another annotation." % arg.default_alias))
kwargs[arg.default_alias] = arg
names = getattr(self, '_fields', None)
i... |
'Returns a new QuerySet instance with the ordering changed.'
| def order_by(self, *field_names):
| assert self.query.can_filter(), 'Cannot reorder a query once a slice has been taken.'
obj = self._clone()
obj.query.clear_ordering()
obj.query.add_ordering(*field_names)
return obj
|
'Returns a new QuerySet instance that will select only distinct results.'
| def distinct(self, true_or_false=True):
| obj = self._clone()
obj.query.distinct = true_or_false
return obj
|
'Adds extra SQL fragments to the query.'
| def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None):
| assert self.query.can_filter(), 'Cannot change a query once a slice has been taken'
clone = self._clone()
clone.query.add_extra(select, select_params, where, params, tables, order_by)
return clone
|
'Reverses the ordering of the QuerySet.'
| def reverse(self):
| clone = self._clone()
clone.query.standard_ordering = (not clone.query.standard_ordering)
return clone
|
'Defers the loading of data for certain fields until they are accessed.
The set of fields to defer is added to any existing set of deferred
fields. The only exception to this is if None is passed in as the only
parameter, in which case all deferrals are removed (None acts as a
reset option).'
| def defer(self, *fields):
| clone = self._clone()
if (fields == (None,)):
clone.query.clear_deferred_loading()
else:
clone.query.add_deferred_loading(fields)
return clone
|
'Essentially, the opposite of defer. Only the fields passed into this
method and that are not already specified as deferred are loaded
immediately when the queryset is evaluated.'
| def only(self, *fields):
| if (fields == (None,)):
raise TypeError('Cannot pass None as an argument to only().')
clone = self._clone()
clone.query.add_immediate_loading(fields)
return clone
|
'Selects which database this QuerySet should excecute it\'s query against.'
| def using(self, alias):
| clone = self._clone()
clone._db = alias
return clone
|
'Returns True if the QuerySet is ordered -- i.e. has an order_by()
clause or a default ordering on the model.'
| def ordered(self):
| if (self.query.extra_order_by or self.query.order_by):
return True
elif (self.query.default_ordering and self.query.model._meta.ordering):
return True
else:
return False
|
'Return the database that will be used if this query is executed now'
| @property
def db(self):
| if self._for_write:
return (self._db or router.db_for_write(self.model))
return (self._db or router.db_for_read(self.model))
|
'Fills the result cache with \'num\' more entries (or until the results
iterator is exhausted).'
| def _fill_cache(self, num=None):
| if self._iter:
try:
for i in range((num or ITER_CHUNK_SIZE)):
self._result_cache.append(self._iter.next())
except StopIteration:
self._iter = None
|
'Indicates that the next filter call and the one following that should
be treated as a single filter. This is only important when it comes to
determining when to reuse tables for many-to-many filters. Required so
that we can filter naturally on the results of related managers.
This doesn\'t return a clone of the curren... | def _next_is_sticky(self):
| self._sticky_filter = True
return self
|
'Checks that we are merging two comparable QuerySet classes. By default
this does nothing, but see the ValuesQuerySet for an example of where
it\'s useful.'
| def _merge_sanity_check(self, other):
| pass
|
'Prepare the query for computing a result that contains aggregate annotations.'
| def _setup_aggregate_query(self, aggregates):
| opts = self.model._meta
if (self.query.group_by is None):
field_names = [f.attname for f in opts.fields]
self.query.add_fields(field_names, False)
self.query.set_group_by()
|
'Returns the internal query\'s SQL and parameters (as a tuple).'
| def _as_sql(self, connection):
| obj = self.values('pk')
if ((obj._db is None) or (connection == connections[obj._db])):
return obj.query.get_compiler(connection=connection).as_nested_sql()
raise ValueError("Can't do subqueries with queries on different DBs.")
|
'Constructs the field_names list that the values query will be
retrieving.
Called by the _clone() method after initializing the rest of the
instance.'
| def _setup_query(self):
| self.query.clear_deferred_loading()
self.query.clear_select_fields()
if self._fields:
self.extra_names = []
self.aggregate_names = []
if ((not self.query.extra) and (not self.query.aggregates)):
self.field_names = list(self._fields)
else:
self.query.de... |
'Cloning a ValuesQuerySet preserves the current fields.'
| def _clone(self, klass=None, setup=False, **kwargs):
| c = super(ValuesQuerySet, self)._clone(klass, **kwargs)
if (not hasattr(c, '_fields')):
c._fields = self._fields[:]
c.field_names = self.field_names
c.extra_names = self.extra_names
c.aggregate_names = self.aggregate_names
if (setup and hasattr(c, '_setup_query')):
c._setup_query... |
'Prepare the query for computing a result that contains aggregate annotations.'
| def _setup_aggregate_query(self, aggregates):
| self.query.set_group_by()
if (self.aggregate_names is not None):
self.aggregate_names.extend(aggregates)
self.query.set_aggregate_mask(self.aggregate_names)
super(ValuesQuerySet, self)._setup_aggregate_query(aggregates)
|
'For ValueQuerySet (and subclasses like ValuesListQuerySet), they can
only be used as nested queries if they\'re already set up to select only
a single field (in which case, that is the field column that is
returned). This differs from QuerySet.as_sql(), where the column to
select is set up by Django.'
| def _as_sql(self, connection):
| if ((self._fields and (len(self._fields) > 1)) or ((not self._fields) and (len(self.model._meta.fields) > 1))):
raise TypeError(('Cannot use a multi-field %s as a filter value.' % self.__class__.__name__))
obj = self._clone()
if ((obj._db is None) or (connection == connection... |
'Validates that we aren\'t trying to do a query like
value__in=qs.values(\'value1\', \'value2\'), which isn\'t valid.'
| def _prepare(self):
| if ((self._fields and (len(self._fields) > 1)) or ((not self._fields) and (len(self.model._meta.fields) > 1))):
raise TypeError(('Cannot use a multi-field %s as a filter value.' % self.__class__.__name__))
return self
|
'Sets up any special features of the query attribute.
Called by the _clone() method after initializing the rest of the
instance.'
| def _setup_query(self):
| self.query.clear_deferred_loading()
self.query = self.query.clone(klass=sql.DateQuery, setup=True)
self.query.select = []
self.query.add_date_select(self._field_name, self._kind, self._order)
|
'Always returns EmptyQuerySet.'
| def all(self):
| return self
|
'Always returns EmptyQuerySet.'
| def filter(self, *args, **kwargs):
| return self
|
'Always returns EmptyQuerySet.'
| def exclude(self, *args, **kwargs):
| return self
|
'Always returns EmptyQuerySet.'
| def complex_filter(self, filter_obj):
| return self
|
'Always returns EmptyQuerySet.'
| def select_related(self, *fields, **kwargs):
| return self
|
'Always returns EmptyQuerySet.'
| def annotate(self, *args, **kwargs):
| return self
|
'Always returns EmptyQuerySet.'
| def order_by(self, *field_names):
| return self
|
'Always returns EmptyQuerySet.'
| def distinct(self, true_or_false=True):
| return self
|
'Always returns EmptyQuerySet.'
| def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None):
| assert self.query.can_filter(), 'Cannot change a query once a slice has been taken'
return self
|
'Always returns EmptyQuerySet.'
| def reverse(self):
| return self
|
'Always returns EmptyQuerySet.'
| def defer(self, *fields):
| return self
|
'Always returns EmptyQuerySet.'
| def only(self, *fields):
| return self
|
'Don\'t update anything.'
| def update(self, **kwargs):
| return 0
|
'Return the database that will be used if this query is executed now'
| @property
def db(self):
| return (self._db or router.db_for_read(self.model))
|
'Selects which database this Raw QuerySet should excecute it\'s query against.'
| def using(self, alias):
| return RawQuerySet(self.raw_query, model=self.model, query=self.query.clone(using=alias), params=self.params, translations=self.translations, using=alias)
|
'A list of model field names in the order they\'ll appear in the
query results.'
| @property
def columns(self):
| if (not hasattr(self, '_columns')):
self._columns = self.query.get_columns()
for (query_name, model_name) in self.translations.items():
try:
index = self._columns.index(query_name)
self._columns[index] = model_name
except ValueError:
... |
'A dict mapping column names to model field names.'
| @property
def model_fields(self):
| if (not hasattr(self, '_model_fields')):
converter = connections[self.db].introspection.table_name_converter
self._model_fields = {}
for field in self.model._meta.fields:
(name, column) = field.get_attname_column()
self._model_fields[converter(column)] = field
ret... |
'Instantiate a new aggregate.
* lookup is the field on which the aggregate operates.
* extra is a dictionary of additional data to provide for the
aggregate definition
Also utilizes the class variables:
* name, the identifier for this aggregate function.'
| def __init__(self, lookup, **extra):
| self.lookup = lookup
self.extra = extra
|
'Add the aggregate to the nominated query.
This method is used to convert the generic Aggregate definition into a
backend-specific definition.
* query is the backend-specific query instance to which the aggregate
is to be added.
* col is a column reference describing the subject field
of the aggregate. It can be an ali... | def add_to_query(self, query, alias, col, source, is_summary):
| klass = getattr(query.aggregates_module, self.name)
aggregate = klass(col, source=source, is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
|
'Retrieves and caches the value from the datastore on the first lookup.
Returns the cached value.'
| def __get__(self, instance, owner):
| from django.db.models.fields import FieldDoesNotExist
assert (instance is not None)
cls = self.model_ref()
data = instance.__dict__
if (data.get(self.field_name, self) is self):
try:
cls._meta.get_field_by_name(self.field_name)
name = self.field_name
except Fi... |
'Deferred loading attributes can be set normally (which means there will
never be a database lookup involved.'
| def __set__(self, instance, value):
| instance.__dict__[self.field_name] = value
|
'Sets the creation counter value for this instance and increments the
class-level copy.'
| def _set_creation_counter(self):
| self.creation_counter = Manager.creation_counter
Manager.creation_counter += 1
|
'Makes a copy of the manager and assigns it to \'model\', which should be
a child of the existing model (used when inheriting a manager from an
abstract base class).'
| def _copy_to_model(self, model):
| assert issubclass(model, self.model)
mgr = copy.copy(self)
mgr._set_creation_counter()
mgr.model = model
mgr._inherited = True
return mgr
|
'Returns a new QuerySet object. Subclasses can override this method
to easily customize the behavior of the Manager.'
| def get_query_set(self):
| return QuerySet(self.model, using=self._db)
|
'Does the internal setup so that the current model is a proxy for
"target".'
| def setup_proxy(self, target):
| self.pk = target._meta.pk
self.proxy_for_model = target
self.db_table = target._meta.db_table
|
'There are a few places where the untranslated verbose name is needed
(so that we get the same value regardless of currently active
locale).'
| def verbose_name_raw(self):
| lang = get_language()
deactivate_all()
raw = force_unicode(self.verbose_name)
activate(lang)
return raw
|
'The getter for self.fields. This returns the list of field objects
available to this model (including through parent models).
Callers are not permitted to modify this list, since it\'s a reference
to this instance (not a copy).'
| def _fields(self):
| try:
self._field_name_cache
except AttributeError:
self._fill_fields_cache()
return self._field_name_cache
|
'Returns a sequence of (field, model) pairs for all fields. The "model"
element is None for fields on the current model. Mostly of use when
constructing queries so that we know which model a field belongs to.'
| def get_fields_with_model(self):
| try:
self._field_cache
except AttributeError:
self._fill_fields_cache()
return self._field_cache
|
'The many-to-many version of get_fields_with_model().'
| def get_m2m_with_model(self):
| try:
self._m2m_cache
except AttributeError:
self._fill_m2m_cache()
return self._m2m_cache.items()
|
'Returns the requested field by name. Raises FieldDoesNotExist on error.'
| def get_field(self, name, many_to_many=True):
| to_search = ((many_to_many and (self.fields + self.many_to_many)) or self.fields)
for f in to_search:
if (f.name == name):
return f
raise FieldDoesNotExist(('%s has no field named %r' % (self.object_name, name)))
|
'Returns the (field_object, model, direct, m2m), where field_object is
the Field instance for the given name, model is the model containing
this field (None for local fields), direct is True if the field exists
on this model, and m2m is True for many-to-many relations. When
\'direct\' is False, \'field_object\' is the ... | def get_field_by_name(self, name):
| try:
try:
return self._name_map[name]
except AttributeError:
cache = self.init_name_map()
return cache[name]
except KeyError:
raise FieldDoesNotExist(('%s has no field named %r' % (self.object_name, name)))
|
'Returns a list of all field names that are possible for this model
(including reverse relation names). This is used for pretty printing
debugging output (a list of choices), so any internal-only field names
are not included.'
| def get_all_field_names(self):
| try:
cache = self._name_map
except AttributeError:
cache = self.init_name_map()
names = cache.keys()
names.sort()
return [val for val in names if (not val.endswith('+'))]
|
'Initialises the field name -> field object mapping.'
| def init_name_map(self):
| cache = {}
for (f, model) in self.get_all_related_m2m_objects_with_model():
cache[f.field.related_query_name()] = (f, model, False, True)
for (f, model) in self.get_all_related_objects_with_model():
cache[f.field.related_query_name()] = (f, model, False, False)
for (f, model) in self.get... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.