desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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() seen_objs = None del_itr = iter(del_query) while 1: seen_o...
'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 = [] field = self.model._meta.get_field(self._field_name, many_to_many=False) assert isinstance(field, DateField), ("%r isn't a DateField." % field.name) self.query.add_d...
'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
'Adds an item to the container. Arguments: * model - the class of the object being added. * pk - the primary key. * obj - the object itself. * parent_model - the model of the parent object that this object was reached through. * parent_obj - the parent object this object was reached through (not used here, but needed i...
def add(self, model, pk, obj, parent_model, parent_obj=None, nullable=False):
if (pk in self.blocked.get(model, {})): return True d = self.data.setdefault(model, SortedDict()) retval = (pk in d) d[pk] = obj if ((parent_model is not None) and (not nullable)): self.children.setdefault(parent_model, []).append(model) return retval
'Returns the models in the order that they should be dealt with (i.e. models with no dependencies first).'
def ordered_keys(self):
dealt_with = SortedDict() models = self.data.keys() while (len(dealt_with) < len(models)): found = False for model in models: if (model in dealt_with): continue children = self.children.setdefault(model, []) if (len([c for c in children if ...
'Fallback for the case where is a cyclic dependency but we don\'t care.'
def unordered_keys(self):
return self.data.keys()
'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...
'Returns a list of (related-object, model) pairs. Similar to get_fields_with_model().'
def get_all_related_objects_with_model(self):
try: self._related_objects_cache except AttributeError: self._fill_related_objects_cache() return self._related_objects_cache.items()
'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)
'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())