1
0
mirror of https://github.com/django/django.git synced 2025-05-29 18:26:29 +00:00

Removed module-level functions for the app cache.

Since the original ones in django.db.models.loading were kept only for
backwards compatibility, there's no need to recreate them. However, many
internals of Django still relied on them.

They were also imported in django.db.models. They never appear in the
documentation, except a quick mention of get_models and get_app in the
1.2 release notes to document an edge case in GIS. I don't think that
makes them a public API.

This commit doesn't change the overall amount of global state but
clarifies that it's tied to the app_cache object instead of hiding it
behind half a dozen functions.
This commit is contained in:
Aymeric Augustin 2013-12-11 23:31:34 +01:00
parent 334551339d
commit 8662654d6d
55 changed files with 226 additions and 220 deletions

View File

@ -0,0 +1 @@
from .cache import app_cache, UnavailableApp # NOQA

View File

@ -12,8 +12,6 @@ from django.utils.module_loading import module_has_submodule
from django.utils._os import upath from django.utils._os import upath
from django.utils import six from django.utils import six
__all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models',
'load_app', 'app_cache_ready')
MODELS_MODULE_NAME = 'models' MODELS_MODULE_NAME = 'models'
@ -361,19 +359,4 @@ class AppCache(BaseAppCache):
self.__dict__ = self.__shared_state self.__dict__ = self.__shared_state
cache = AppCache() app_cache = AppCache()
# These methods were always module level, so are kept that way for backwards
# compatibility.
get_apps = cache.get_apps
get_app_package = cache.get_app_package
get_app_path = cache.get_app_path
get_app_paths = cache.get_app_paths
get_app = cache.get_app
get_app_errors = cache.get_app_errors
get_models = cache.get_models
get_model = cache.get_model
register_models = cache.register_models
load_app = cache.load_app
app_cache_ready = cache.app_cache_ready

View File

@ -1,3 +1,4 @@
from django.apps import app_cache
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.db import models from django.db import models
from django.db.models.fields import FieldDoesNotExist from django.db.models.fields import FieldDoesNotExist
@ -17,7 +18,7 @@ class BaseValidator(object):
def __init__(self): def __init__(self):
# Before we can introspect models, they need to be fully loaded so that # Before we can introspect models, they need to be fully loaded so that
# inter-relations are set up correctly. We force that here. # inter-relations are set up correctly. We force that here.
models.get_apps() app_cache.get_apps()
def validate(self, cls, model): def validate(self, cls, model):
for m in dir(self): for m in dir(self):

View File

@ -4,6 +4,7 @@ import os
import re import re
from django import template from django import template
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admin.views.decorators import staff_member_required
@ -182,7 +183,7 @@ class ModelIndexView(BaseAdminDocsView):
template_name = 'admin_doc/model_index.html' template_name = 'admin_doc/model_index.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
m_list = [m._meta for m in models.get_models()] m_list = [m._meta for m in app_cache.get_models()]
kwargs.update({'models': m_list}) kwargs.update({'models': m_list})
return super(ModelIndexView, self).get_context_data(**kwargs) return super(ModelIndexView, self).get_context_data(**kwargs)
@ -193,11 +194,11 @@ class ModelDetailView(BaseAdminDocsView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# Get the model class. # Get the model class.
try: try:
app_mod = models.get_app(self.kwargs['app_label']) app_mod = app_cache.get_app(self.kwargs['app_label'])
except ImproperlyConfigured: except ImproperlyConfigured:
raise Http404(_("App %r not found") % self.kwargs['app_label']) raise Http404(_("App %r not found") % self.kwargs['app_label'])
model = None model = None
for m in models.get_models(app_mod): for m in app_cache.get_models(app_mod):
if m._meta.model_name == self.kwargs['model_name']: if m._meta.model_name == self.kwargs['model_name']:
model = m model = m
break break

View File

@ -123,13 +123,13 @@ def get_user_model():
""" """
Returns the User model that is active in this project. Returns the User model that is active in this project.
""" """
from django.db.models import get_model from django.apps import app_cache
try: try:
app_label, model_name = settings.AUTH_USER_MODEL.split('.') app_label, model_name = settings.AUTH_USER_MODEL.split('.')
except ValueError: except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'") raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
user_model = get_model(app_label, model_name) user_model = app_cache.get_model(app_label, model_name)
if user_model is None: if user_model is None:
raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL) raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)
return user_model return user_model

View File

@ -6,12 +6,13 @@ from __future__ import unicode_literals
import getpass import getpass
import unicodedata import unicodedata
from django.apps import app_cache, UnavailableApp
from django.contrib.auth import (models as auth_app, get_permission_codename, from django.contrib.auth import (models as auth_app, get_permission_codename,
get_user_model) get_user_model)
from django.core import exceptions from django.core import exceptions
from django.core.management.base import CommandError from django.core.management.base import CommandError
from django.db import DEFAULT_DB_ALIAS, router from django.db import DEFAULT_DB_ALIAS, router
from django.db.models import get_model, get_models, signals, UnavailableApp from django.db.models import signals
from django.utils.encoding import DEFAULT_LOCALE_ENCODING from django.utils.encoding import DEFAULT_LOCALE_ENCODING
from django.utils import six from django.utils import six
from django.utils.six.moves import input from django.utils.six.moves import input
@ -61,7 +62,7 @@ def _check_permission_clashing(custom, builtin, ctype):
def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs): def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs):
try: try:
get_model('auth', 'Permission') app_cache.get_model('auth', 'Permission')
except UnavailableApp: except UnavailableApp:
return return
@ -70,7 +71,7 @@ def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kw
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
app_models = get_models(app) app_models = app_cache.get_models(app)
# This will hold the permissions we're looking for as # This will hold the permissions we're looking for as
# (content_type, (codename, name)) # (content_type, (codename, name))
@ -119,7 +120,7 @@ def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kw
def create_superuser(app, created_models, verbosity, db, **kwargs): def create_superuser(app, created_models, verbosity, db, **kwargs):
try: try:
get_model('auth', 'Permission') app_cache.get_model('auth', 'Permission')
UserModel = get_user_model() UserModel = get_user_model()
except UnavailableApp: except UnavailableApp:
return return

View File

@ -1,7 +1,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from datetime import date from datetime import date
from django.apps.cache import get_app from django.apps import app_cache
from django.contrib.auth import models, management from django.contrib.auth import models, management
from django.contrib.auth.management import create_permissions from django.contrib.auth.management import create_permissions
from django.contrib.auth.management.commands import changepassword from django.contrib.auth.management.commands import changepassword
@ -184,21 +184,21 @@ class CustomUserModelValidationTestCase(TestCase):
def test_required_fields_is_list(self): def test_required_fields_is_list(self):
"REQUIRED_FIELDS should be a list." "REQUIRED_FIELDS should be a list."
new_io = StringIO() new_io = StringIO()
get_validation_errors(new_io, get_app('auth')) get_validation_errors(new_io, app_cache.get_app('auth'))
self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue()) self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue())
@override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields') @override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields')
def test_username_not_in_required_fields(self): def test_username_not_in_required_fields(self):
"USERNAME_FIELD should not appear in REQUIRED_FIELDS." "USERNAME_FIELD should not appear in REQUIRED_FIELDS."
new_io = StringIO() new_io = StringIO()
get_validation_errors(new_io, get_app('auth')) get_validation_errors(new_io, app_cache.get_app('auth'))
self.assertIn("The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue()) self.assertIn("The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue())
@override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername') @override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername')
def test_username_non_unique(self): def test_username_non_unique(self):
"A non-unique USERNAME_FIELD should raise a model validation error." "A non-unique USERNAME_FIELD should raise a model validation error."
new_io = StringIO() new_io = StringIO()
get_validation_errors(new_io, get_app('auth')) get_validation_errors(new_io, app_cache.get_app('auth'))
self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue()) self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue())

View File

@ -1,4 +1,5 @@
from django import http from django import http
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.contrib import comments from django.contrib import comments
from django.contrib.comments import signals from django.contrib.comments import signals
@ -48,7 +49,7 @@ def post_comment(request, next=None, using=None):
if ctype is None or object_pk is None: if ctype is None or object_pk is None:
return CommentPostBadRequest("Missing content_type or object_pk field.") return CommentPostBadRequest("Missing content_type or object_pk field.")
try: try:
model = models.get_model(*ctype.split(".", 1)) model = app_cache.get_model(*ctype.split(".", 1))
target = model._default_manager.using(using).get(pk=object_pk) target = model._default_manager.using(using).get(pk=object_pk)
except TypeError: except TypeError:
return CommentPostBadRequest( return CommentPostBadRequest(

View File

@ -1,6 +1,7 @@
from django.apps import app_cache, UnavailableApp
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.db import DEFAULT_DB_ALIAS, router from django.db import DEFAULT_DB_ALIAS, router
from django.db.models import get_apps, get_model, get_models, signals, UnavailableApp from django.db.models import signals
from django.utils.encoding import smart_text from django.utils.encoding import smart_text
from django.utils import six from django.utils import six
from django.utils.six.moves import input from django.utils.six.moves import input
@ -12,7 +13,7 @@ def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, *
entries that no longer have a matching model class. entries that no longer have a matching model class.
""" """
try: try:
get_model('contenttypes', 'ContentType') app_cache.get_model('contenttypes', 'ContentType')
except UnavailableApp: except UnavailableApp:
return return
@ -20,7 +21,7 @@ def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, *
return return
ContentType.objects.clear_cache() ContentType.objects.clear_cache()
app_models = get_models(app) app_models = app_cache.get_models(app)
if not app_models: if not app_models:
return return
# They all have the same app_label, get the first one. # They all have the same app_label, get the first one.
@ -85,7 +86,7 @@ If you're unsure, answer 'no'.
def update_all_contenttypes(verbosity=2, **kwargs): def update_all_contenttypes(verbosity=2, **kwargs):
for app in get_apps(): for app in app_cache.get_apps():
update_contenttypes(app, None, verbosity, **kwargs) update_contenttypes(app, None, verbosity, **kwargs)
signals.post_migrate.connect(update_contenttypes) signals.post_migrate.connect(update_contenttypes)

View File

@ -1,3 +1,4 @@
from django.apps import app_cache
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_text, force_text from django.utils.encoding import smart_text, force_text
@ -156,7 +157,7 @@ class ContentType(models.Model):
def model_class(self): def model_class(self):
"Returns the Python model class for this type of content." "Returns the Python model class for this type of content."
return models.get_model(self.app_label, self.model, return app_cache.get_model(self.app_label, self.model,
only_installed=False) only_installed=False)
def get_object_for_this_type(self, **kwargs): def get_object_for_this_type(self, **kwargs):

View File

@ -1,3 +1,4 @@
from django.apps import app_cache
from django.core import urlresolvers from django.core import urlresolvers
from django.contrib.sitemaps import Sitemap from django.contrib.sitemaps import Sitemap
from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.fields import GeometryField
@ -25,7 +26,7 @@ class KMLSitemap(Sitemap):
""" """
kml_sources = [] kml_sources = []
if sources is None: if sources is None:
sources = models.get_models() sources = app_cache.get_models()
for source in sources: for source in sources:
if isinstance(source, models.base.ModelBase): if isinstance(source, models.base.ModelBase):
for field in source._meta.fields: for field in source._meta.fields:

View File

@ -2,6 +2,7 @@ from __future__ import unicode_literals
import warnings import warnings
from django.apps import app_cache
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
from django.template import loader from django.template import loader
from django.contrib.sites.models import get_current_site from django.contrib.sites.models import get_current_site
@ -9,7 +10,6 @@ from django.core import urlresolvers
from django.core.paginator import EmptyPage, PageNotAnInteger from django.core.paginator import EmptyPage, PageNotAnInteger
from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.fields import GeometryField
from django.db import connections, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
from django.db.models import get_model
from django.db.models.fields import FieldDoesNotExist from django.db.models.fields import FieldDoesNotExist
from django.utils import six from django.utils import six
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
@ -81,7 +81,7 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB
must be that of a geographic field. must be that of a geographic field.
""" """
placemarks = [] placemarks = []
klass = get_model(label, model) klass = app_cache.get_model(label, model)
if not klass: if not klass:
raise Http404('You must supply a valid app label and module name. Got "%s.%s"' % (label, model)) raise Http404('You must supply a valid app label and module name. Got "%s.%s"' % (label, model))

View File

@ -1,5 +1,6 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from django.apps import app_cache
from django.db import models from django.db import models
@ -31,7 +32,7 @@ def check_boolean_field_default_value():
warns the user that the default has changed from False to Null. warns the user that the default has changed from False to Null.
""" """
fields = [] fields = []
for cls in models.get_models(): for cls in app_cache.get_models():
opts = cls._meta opts = cls._meta
for f in opts.local_fields: for f in opts.local_fields:
if isinstance(f, models.BooleanField) and not f.has_default(): if isinstance(f, models.BooleanField) and not f.has_default():

View File

@ -342,11 +342,11 @@ class AppCommand(BaseCommand):
args = '<appname appname ...>' args = '<appname appname ...>'
def handle(self, *app_labels, **options): def handle(self, *app_labels, **options):
from django.db import models from django.apps import app_cache
if not app_labels: if not app_labels:
raise CommandError('Enter at least one appname.') raise CommandError('Enter at least one appname.')
try: try:
app_list = [models.get_app(app_label) for app_label in app_labels] app_list = [app_cache.get_app(app_label) for app_label in app_labels]
except (ImproperlyConfigured, ImportError) as e: except (ImproperlyConfigured, ImportError) as e:
raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
output = [] output = []

View File

@ -38,7 +38,7 @@ class Command(BaseCommand):
args = '[appname appname.ModelName ...]' args = '[appname appname.ModelName ...]'
def handle(self, *app_labels, **options): def handle(self, *app_labels, **options):
from django.db.models import get_app, get_apps, get_model from django.apps import app_cache
format = options.get('format') format = options.get('format')
indent = options.get('indent') indent = options.get('indent')
@ -64,13 +64,13 @@ class Command(BaseCommand):
for exclude in excludes: for exclude in excludes:
if '.' in exclude: if '.' in exclude:
app_label, model_name = exclude.split('.', 1) app_label, model_name = exclude.split('.', 1)
model_obj = get_model(app_label, model_name) model_obj = app_cache.get_model(app_label, model_name)
if not model_obj: if not model_obj:
raise CommandError('Unknown model in excludes: %s' % exclude) raise CommandError('Unknown model in excludes: %s' % exclude)
excluded_models.add(model_obj) excluded_models.add(model_obj)
else: else:
try: try:
app_obj = get_app(exclude) app_obj = app_cache.get_app(exclude)
excluded_apps.add(app_obj) excluded_apps.add(app_obj)
except ImproperlyConfigured: except ImproperlyConfigured:
raise CommandError('Unknown app in excludes: %s' % exclude) raise CommandError('Unknown app in excludes: %s' % exclude)
@ -78,7 +78,7 @@ class Command(BaseCommand):
if len(app_labels) == 0: if len(app_labels) == 0:
if primary_keys: if primary_keys:
raise CommandError("You can only use --pks option with one model") raise CommandError("You can only use --pks option with one model")
app_list = OrderedDict((app, None) for app in get_apps() if app not in excluded_apps) app_list = OrderedDict((app, None) for app in app_cache.get_apps() if app not in excluded_apps)
else: else:
if len(app_labels) > 1 and primary_keys: if len(app_labels) > 1 and primary_keys:
raise CommandError("You can only use --pks option with one model") raise CommandError("You can only use --pks option with one model")
@ -87,12 +87,12 @@ class Command(BaseCommand):
try: try:
app_label, model_label = label.split('.') app_label, model_label = label.split('.')
try: try:
app = get_app(app_label) app = app_cache.get_app(app_label)
except ImproperlyConfigured: except ImproperlyConfigured:
raise CommandError("Unknown application: %s" % app_label) raise CommandError("Unknown application: %s" % app_label)
if app in excluded_apps: if app in excluded_apps:
continue continue
model = get_model(app_label, model_label) model = app_cache.get_model(app_label, model_label)
if model is None: if model is None:
raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) raise CommandError("Unknown model: %s.%s" % (app_label, model_label))
@ -107,7 +107,7 @@ class Command(BaseCommand):
# This is just an app - no model qualifier # This is just an app - no model qualifier
app_label = label app_label = label
try: try:
app = get_app(app_label) app = app_cache.get_app(app_label)
except ImproperlyConfigured: except ImproperlyConfigured:
raise CommandError("Unknown application: %s" % app_label) raise CommandError("Unknown application: %s" % app_label)
if app in excluded_apps: if app in excluded_apps:
@ -160,13 +160,13 @@ def sort_dependencies(app_list):
is serialized before a normal model, and any model with a natural key is serialized before a normal model, and any model with a natural key
dependency has it's dependencies serialized first. dependency has it's dependencies serialized first.
""" """
from django.db.models import get_model, get_models from django.apps import app_cache
# Process the list of models, and get the list of dependencies # Process the list of models, and get the list of dependencies
model_dependencies = [] model_dependencies = []
models = set() models = set()
for app, model_list in app_list: for app, model_list in app_list:
if model_list is None: if model_list is None:
model_list = get_models(app) model_list = app_cache.get_models(app)
for model in model_list: for model in model_list:
models.add(model) models.add(model)
@ -174,7 +174,7 @@ def sort_dependencies(app_list):
if hasattr(model, 'natural_key'): if hasattr(model, 'natural_key'):
deps = getattr(model.natural_key, 'dependencies', []) deps = getattr(model.natural_key, 'dependencies', [])
if deps: if deps:
deps = [get_model(*d.split('.')) for d in deps] deps = [app_cache.get_model(*d.split('.')) for d in deps]
else: else:
deps = [] deps = []

View File

@ -2,8 +2,9 @@ import sys
from importlib import import_module from importlib import import_module
from optparse import make_option from optparse import make_option
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.db import connections, router, transaction, DEFAULT_DB_ALIAS
from django.core.management import call_command from django.core.management import call_command
from django.core.management.base import NoArgsCommand, CommandError from django.core.management.base import NoArgsCommand, CommandError
from django.core.management.color import no_style from django.core.management.color import no_style
@ -93,6 +94,6 @@ Are you sure you want to do this?
# Emit the post migrate signal. This allows individual applications to # Emit the post migrate signal. This allows individual applications to
# respond as if the database had been migrated from scratch. # respond as if the database had been migrated from scratch.
all_models = [] all_models = []
for app in models.get_apps(): for app in app_cache.get_apps():
all_models.extend(router.get_migratable_models(app, database, include_auto_created=True)) all_models.extend(router.get_migratable_models(app, database, include_auto_created=True))
emit_post_migrate_signal(set(all_models), verbosity, interactive, database) emit_post_migrate_signal(set(all_models), verbosity, interactive, database)

View File

@ -7,13 +7,13 @@ import warnings
import zipfile import zipfile
from optparse import make_option from optparse import make_option
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core import serializers from django.core import serializers
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style from django.core.management.color import no_style
from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS, from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS,
IntegrityError, DatabaseError) IntegrityError, DatabaseError)
from django.db.models import get_app_paths
from django.utils import lru_cache from django.utils import lru_cache
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.functional import cached_property from django.utils.functional import cached_property
@ -230,7 +230,7 @@ class Command(BaseCommand):
current directory. current directory.
""" """
dirs = [] dirs = []
for path in get_app_paths(): for path in app_cache.get_app_paths():
d = os.path.join(path, 'fixtures') d = os.path.join(path, 'fixtures')
if os.path.isdir(d): if os.path.isdir(d):
dirs.append(d) dirs.append(d)

View File

@ -3,7 +3,7 @@ import os
import operator import operator
from optparse import make_option from optparse import make_option
from django.apps.cache import cache from django.apps import app_cache
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.db import connections, DEFAULT_DB_ALIAS, migrations from django.db import connections, DEFAULT_DB_ALIAS, migrations
@ -38,7 +38,7 @@ class Command(BaseCommand):
bad_app_labels = set() bad_app_labels = set()
for app_label in app_labels: for app_label in app_labels:
try: try:
cache.get_app(app_label) app_cache.get_app(app_label)
except ImproperlyConfigured: except ImproperlyConfigured:
bad_app_labels.add(app_label) bad_app_labels.add(app_label)
if bad_app_labels: if bad_app_labels:
@ -73,7 +73,7 @@ class Command(BaseCommand):
# Detect changes # Detect changes
autodetector = MigrationAutodetector( autodetector = MigrationAutodetector(
loader.graph.project_state(), loader.graph.project_state(),
ProjectState.from_app_cache(cache), ProjectState.from_app_cache(app_cache),
InteractiveMigrationQuestioner(specified_apps=app_labels), InteractiveMigrationQuestioner(specified_apps=app_labels),
) )
changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None) changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None)

View File

@ -6,13 +6,13 @@ from importlib import import_module
import itertools import itertools
import traceback import traceback
from django.apps.cache import cache from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core.management import call_command from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style from django.core.management.color import no_style
from django.core.management.sql import custom_sql_for_model, emit_post_migrate_signal, emit_pre_migrate_signal from django.core.management.sql import custom_sql_for_model, emit_post_migrate_signal, emit_pre_migrate_signal
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS from django.db import connections, router, transaction, DEFAULT_DB_ALIAS
from django.db.migrations.executor import MigrationExecutor from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.loader import MigrationLoader, AmbiguityError from django.db.migrations.loader import MigrationLoader, AmbiguityError
from django.db.migrations.state import ProjectState from django.db.migrations.state import ProjectState
@ -136,7 +136,7 @@ class Command(BaseCommand):
# If there's changes that aren't in migrations yet, tell them how to fix it. # If there's changes that aren't in migrations yet, tell them how to fix it.
autodetector = MigrationAutodetector( autodetector = MigrationAutodetector(
executor.loader.graph.project_state(), executor.loader.graph.project_state(),
ProjectState.from_app_cache(cache), ProjectState.from_app_cache(app_cache),
) )
changes = autodetector.changes(graph=executor.loader.graph) changes = autodetector.changes(graph=executor.loader.graph)
if changes: if changes:
@ -182,7 +182,7 @@ class Command(BaseCommand):
all_models = [ all_models = [
(app.__name__.split('.')[-2], (app.__name__.split('.')[-2],
router.get_migratable_models(app, connection.alias, include_auto_created=True)) router.get_migratable_models(app, connection.alias, include_auto_created=True))
for app in models.get_apps() if app.__name__.split('.')[-2] in apps for app in app_cache.get_apps() if app.__name__.split('.')[-2] in apps
] ]
def model_installed(model): def model_installed(model):

View File

@ -66,8 +66,8 @@ class Command(NoArgsCommand):
def handle_noargs(self, **options): def handle_noargs(self, **options):
# XXX: (Temporary) workaround for ticket #1796: force early loading of all # XXX: (Temporary) workaround for ticket #1796: force early loading of all
# models from installed apps. # models from installed apps.
from django.apps.cache import get_models from django.apps import app_cache
get_models() app_cache.get_models()
use_plain = options.get('plain', False) use_plain = options.get('plain', False)
no_startup = options.get('no_startup', False) no_startup = options.get('no_startup', False)

View File

@ -2,8 +2,9 @@ from __future__ import unicode_literals
from optparse import make_option from optparse import make_option
from django.apps import app_cache
from django.core.management.base import AppCommand from django.core.management.base import AppCommand
from django.db import connections, models, DEFAULT_DB_ALIAS from django.db import connections, DEFAULT_DB_ALIAS
class Command(AppCommand): class Command(AppCommand):
@ -20,4 +21,4 @@ class Command(AppCommand):
def handle_app(self, app, **options): def handle_app(self, app, **options):
connection = connections[options.get('database')] connection = connections[options.get('database')]
return '\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))) return '\n'.join(connection.ops.sequence_reset_sql(self.style, app_cache.get_models(app, include_auto_created=True)))

View File

@ -5,6 +5,7 @@ import os
import re import re
import warnings import warnings
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core.management.base import CommandError from django.core.management.base import CommandError
from django.db import models, router from django.db import models, router
@ -24,7 +25,7 @@ def sql_create(app, style, connection):
# We trim models from the current app so that the sqlreset command does not # We trim models from the current app so that the sqlreset command does not
# generate invalid SQL (leaving models out of known_models is harmless, so # generate invalid SQL (leaving models out of known_models is harmless, so
# we can be conservative). # we can be conservative).
app_models = models.get_models(app, include_auto_created=True) app_models = app_cache.get_models(app, include_auto_created=True)
final_output = [] final_output = []
tables = connection.introspection.table_names() tables = connection.introspection.table_names()
known_models = set(model for model in connection.introspection.installed_models(tables) if model not in app_models) known_models = set(model for model in connection.introspection.installed_models(tables) if model not in app_models)
@ -168,7 +169,7 @@ def _split_statements(content):
def custom_sql_for_model(model, style, connection): def custom_sql_for_model(model, style, connection):
opts = model._meta opts = model._meta
app_dirs = [] app_dirs = []
app_dir = models.get_app_path(model._meta.app_label) app_dir = app_cache.get_app_path(model._meta.app_label)
app_dirs.append(os.path.normpath(os.path.join(app_dir, 'sql'))) app_dirs.append(os.path.normpath(os.path.join(app_dir, 'sql')))
# Deprecated location -- remove in Django 1.9 # Deprecated location -- remove in Django 1.9
@ -206,7 +207,7 @@ def custom_sql_for_model(model, style, connection):
def emit_pre_migrate_signal(create_models, verbosity, interactive, db): def emit_pre_migrate_signal(create_models, verbosity, interactive, db):
# Emit the pre_migrate signal for every application. # Emit the pre_migrate signal for every application.
for app in models.get_apps(): for app in app_cache.get_apps():
app_name = app.__name__.split('.')[-2] app_name = app.__name__.split('.')[-2]
if verbosity >= 2: if verbosity >= 2:
print("Running pre-migrate handlers for application %s" % app_name) print("Running pre-migrate handlers for application %s" % app_name)
@ -219,7 +220,7 @@ def emit_pre_migrate_signal(create_models, verbosity, interactive, db):
def emit_post_migrate_signal(created_models, verbosity, interactive, db): def emit_post_migrate_signal(created_models, verbosity, interactive, db):
# Emit the post_migrate signal for every application. # Emit the post_migrate signal for every application.
for app in models.get_apps(): for app in app_cache.get_apps():
app_name = app.__name__.split('.')[-2] app_name = app.__name__.split('.')[-2]
if verbosity >= 2: if verbosity >= 2:
print("Running post-migrate handlers for application %s" % app_name) print("Running post-migrate handlers for application %s" % app_name)

View File

@ -26,16 +26,16 @@ def get_validation_errors(outfile, app=None):
validates all models of all installed apps. Writes errors, if any, to outfile. validates all models of all installed apps. Writes errors, if any, to outfile.
Returns number of errors. Returns number of errors.
""" """
from django.apps.cache import get_app_errors from django.apps import app_cache
from django.db import connection, models from django.db import connection, models
from django.db.models.deletion import SET_NULL, SET_DEFAULT from django.db.models.deletion import SET_NULL, SET_DEFAULT
e = ModelErrorCollection(outfile) e = ModelErrorCollection(outfile)
for (app_name, error) in get_app_errors().items(): for (app_name, error) in app_cache.get_app_errors().items():
e.add(app_name, error) e.add(app_name, error)
for cls in models.get_models(app, include_swapped=True): for cls in app_cache.get_models(app, include_swapped=True):
opts = cls._meta opts = cls._meta
# Check swappable attribute. # Check swappable attribute.
@ -45,7 +45,7 @@ def get_validation_errors(outfile, app=None):
except ValueError: except ValueError:
e.add(opts, "%s is not of the form 'app_label.app_name'." % opts.swappable) e.add(opts, "%s is not of the form 'app_label.app_name'." % opts.swappable)
continue continue
if not models.get_model(app_label, model_name): if not app_cache.get_model(app_label, model_name):
e.add(opts, "Model has been swapped out for '%s' which has not been installed or is abstract." % opts.swapped) e.add(opts, "Model has been swapped out for '%s' which has not been installed or is abstract." % opts.swapped)
# No need to perform any other validation checks on a swapped model. # No need to perform any other validation checks on a swapped model.
continue continue
@ -155,7 +155,7 @@ def get_validation_errors(outfile, app=None):
# Check to see if the related field will clash with any existing # Check to see if the related field will clash with any existing
# fields, m2m fields, m2m related objects or related objects # fields, m2m fields, m2m related objects or related objects
if f.rel: if f.rel:
if f.rel.to not in models.get_models(): if f.rel.to not in app_cache.get_models():
# If the related model is swapped, provide a hint; # If the related model is swapped, provide a hint;
# otherwise, the model just hasn't been installed. # otherwise, the model just hasn't been installed.
if not isinstance(f.rel.to, six.string_types) and f.rel.to._meta.swapped: if not isinstance(f.rel.to, six.string_types) and f.rel.to._meta.swapped:
@ -210,7 +210,7 @@ def get_validation_errors(outfile, app=None):
# Check to see if the related m2m field will clash with any # Check to see if the related m2m field will clash with any
# existing fields, m2m fields, m2m related objects or related # existing fields, m2m fields, m2m related objects or related
# objects # objects
if f.rel.to not in models.get_models(): if f.rel.to not in app_cache.get_models():
# If the related model is swapped, provide a hint; # If the related model is swapped, provide a hint;
# otherwise, the model just hasn't been installed. # otherwise, the model just hasn't been installed.
if not isinstance(f.rel.to, six.string_types) and f.rel.to._meta.swapped: if not isinstance(f.rel.to, six.string_types) and f.rel.to._meta.swapped:
@ -268,7 +268,7 @@ def get_validation_errors(outfile, app=None):
) )
else: else:
seen_to = True seen_to = True
if f.rel.through not in models.get_models(include_auto_created=True): if f.rel.through not in app_cache.get_models(include_auto_created=True):
e.add(opts, "'%s' specifies an m2m relation through model " e.add(opts, "'%s' specifies an m2m relation through model "
"%s, which has not been installed." % (f.name, f.rel.through)) "%s, which has not been installed." % (f.name, f.rel.through))
signature = (f.rel.to, cls, f.rel.through) signature = (f.rel.to, cls, f.rel.through)

View File

@ -3,6 +3,7 @@ Module for abstract serializer/unserializer base classes.
""" """
import warnings import warnings
from django.apps import app_cache
from django.db import models from django.db import models
from django.utils import six from django.utils import six
@ -139,7 +140,7 @@ class Deserializer(six.Iterator):
# hack to make sure that the models have all been loaded before # hack to make sure that the models have all been loaded before
# deserialization starts (otherwise subclass calls to get_model() # deserialization starts (otherwise subclass calls to get_model()
# and friends might fail...) # and friends might fail...)
models.get_apps() app_cache.get_apps()
def __iter__(self): def __iter__(self):
return self return self

View File

@ -5,6 +5,7 @@ other serializers.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core.serializers import base from django.core.serializers import base
from django.db import models, DEFAULT_DB_ALIAS from django.db import models, DEFAULT_DB_ALIAS
@ -87,7 +88,7 @@ def Deserializer(object_list, **options):
db = options.pop('using', DEFAULT_DB_ALIAS) db = options.pop('using', DEFAULT_DB_ALIAS)
ignore = options.pop('ignorenonexistent', False) ignore = options.pop('ignorenonexistent', False)
models.get_apps() app_cache.get_apps()
for d in object_list: for d in object_list:
# Look up the model and starting build a dict of data for it. # Look up the model and starting build a dict of data for it.
Model = _get_model(d["model"]) Model = _get_model(d["model"])
@ -153,7 +154,7 @@ def _get_model(model_identifier):
Helper to look up a model from an "app_label.model_name" string. Helper to look up a model from an "app_label.model_name" string.
""" """
try: try:
Model = models.get_model(*model_identifier.split(".")) Model = app_cache.get_model(*model_identifier.split("."))
except TypeError: except TypeError:
Model = None Model = None
if Model is None: if Model is None:

View File

@ -4,6 +4,7 @@ XML serializer.
from __future__ import unicode_literals from __future__ import unicode_literals
from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core.serializers import base from django.core.serializers import base
from django.db import models, DEFAULT_DB_ALIAS from django.db import models, DEFAULT_DB_ALIAS
@ -276,7 +277,7 @@ class Deserializer(base.Deserializer):
"<%s> node is missing the required '%s' attribute" "<%s> node is missing the required '%s' attribute"
% (node.nodeName, attr)) % (node.nodeName, attr))
try: try:
Model = models.get_model(*model_identifier.split(".")) Model = app_cache.get_model(*model_identifier.split("."))
except TypeError: except TypeError:
Model = None Model = None
if Model is None: if Model is None:

View File

@ -1268,9 +1268,10 @@ class BaseDatabaseIntrospection(object):
If only_existing is True, the resulting list will only include the tables If only_existing is True, the resulting list will only include the tables
that actually exist in the database. that actually exist in the database.
""" """
from django.db import models, router from django.apps import app_cache
from django.db import router
tables = set() tables = set()
for app in models.get_apps(): for app in app_cache.get_apps():
for model in router.get_migratable_models(app, self.connection.alias): for model in router.get_migratable_models(app, self.connection.alias):
if not model._meta.managed: if not model._meta.managed:
continue continue
@ -1288,9 +1289,10 @@ class BaseDatabaseIntrospection(object):
def installed_models(self, tables): def installed_models(self, tables):
"Returns a set of all models represented by the provided list of table names." "Returns a set of all models represented by the provided list of table names."
from django.db import models, router from django.apps import app_cache
from django.db import router
all_models = [] all_models = []
for app in models.get_apps(): for app in app_cache.get_apps():
all_models.extend(router.get_migratable_models(app, self.connection.alias)) all_models.extend(router.get_migratable_models(app, self.connection.alias))
tables = list(map(self.table_name_converter, tables)) tables = list(map(self.table_name_converter, tables))
return set([ return set([
@ -1300,9 +1302,10 @@ class BaseDatabaseIntrospection(object):
def sequence_list(self): def sequence_list(self):
"Returns a list of information about all DB sequences for all models in all apps." "Returns a list of information about all DB sequences for all models in all apps."
from django.apps import app_cache
from django.db import models, router from django.db import models, router
apps = models.get_apps() apps = app_cache.get_apps()
sequence_list = [] sequence_list = []
for app in apps: for app in apps:

View File

@ -1,7 +1,8 @@
from importlib import import_module
import os import os
import sys import sys
from importlib import import_module
from django.apps.cache import cache from django.apps import app_cache
from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.recorder import MigrationRecorder
from django.db.migrations.graph import MigrationGraph from django.db.migrations.graph import MigrationGraph
from django.utils import six from django.utils import six
@ -45,7 +46,7 @@ class MigrationLoader(object):
if app_label in settings.MIGRATION_MODULES: if app_label in settings.MIGRATION_MODULES:
return settings.MIGRATION_MODULES[app_label] return settings.MIGRATION_MODULES[app_label]
else: else:
return '%s.migrations' % cache.get_app_package(app_label) return '%s.migrations' % app_cache.get_app_package(app_label)
def load_disk(self): def load_disk(self):
""" """
@ -54,7 +55,7 @@ class MigrationLoader(object):
self.disk_migrations = {} self.disk_migrations = {}
self.unmigrated_apps = set() self.unmigrated_apps = set()
self.migrated_apps = set() self.migrated_apps = set()
for app in cache.get_apps(): for app in app_cache.get_apps():
# Get the migrations module directory # Get the migrations module directory
app_label = app.__name__.split(".")[-2] app_label = app.__name__.split(".")[-2]
module_name = self.migrations_module(app_label) module_name = self.migrations_module(app_label)

View File

@ -2,7 +2,7 @@ import importlib
import os import os
import sys import sys
from django.apps.cache import cache from django.apps import app_cache
from django.utils import datetime_safe from django.utils import datetime_safe
from django.utils.six.moves import input from django.utils.six.moves import input
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
@ -29,7 +29,7 @@ class MigrationQuestioner(object):
# Apps from the new app template will have these; the python # Apps from the new app template will have these; the python
# file check will ensure we skip South ones. # file check will ensure we skip South ones.
try: try:
models_module = cache.get_app(app_label) models_module = app_cache.get_app(app_label)
except ImproperlyConfigured: # It's a fake app except ImproperlyConfigured: # It's a fake app
return self.defaults.get("ask_initial", False) return self.defaults.get("ask_initial", False)
migrations_import_path = "%s.migrations" % models_module.__package__ migrations_import_path = "%s.migrations" % models_module.__package__

View File

@ -1,9 +1,11 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import datetime import datetime
import types
import os
from importlib import import_module from importlib import import_module
from django.apps.cache import cache import os
import types
from django.apps import app_cache
from django.db import models from django.db import models
from django.db.migrations.loader import MigrationLoader from django.db.migrations.loader import MigrationLoader
from django.utils.encoding import force_text from django.utils.encoding import force_text
@ -67,9 +69,9 @@ class MigrationWriter(object):
migrations_module = import_module(migrations_package_name) migrations_module = import_module(migrations_package_name)
basedir = os.path.dirname(migrations_module.__file__) basedir = os.path.dirname(migrations_module.__file__)
except ImportError: except ImportError:
app = cache.get_app(self.migration.app_label) app = app_cache.get_app(self.migration.app_label)
app_path = cache._get_app_path(app) app_path = app_cache._get_app_path(app)
app_package_name = cache._get_app_package(app) app_package_name = app_cache._get_app_package(app)
migrations_package_basename = migrations_package_name.split(".")[-1] migrations_package_basename = migrations_package_name.split(".")[-1]
# Alright, see if it's a direct submodule of the app # Alright, see if it's a direct submodule of the app

View File

@ -1,8 +1,5 @@
from functools import wraps from functools import wraps
from django.apps.cache import ( # NOQA
get_apps, get_app_path, get_app_paths, get_app, get_models, get_model,
register_models, UnavailableApp)
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured # NOQA from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured # NOQA
from django.db.models.query import Q, QuerySet, Prefetch # NOQA from django.db.models.query import Q, QuerySet, Prefetch # NOQA
from django.db.models.expressions import F # NOQA from django.db.models.expressions import F # NOQA

View File

@ -5,7 +5,8 @@ import sys
from functools import update_wrapper from functools import update_wrapper
from django.utils.six.moves import zip from django.utils.six.moves import zip
from django.apps.cache import get_model, MODELS_MODULE_NAME from django.apps import app_cache
from django.apps.cache import MODELS_MODULE_NAME
import django.db.models.manager # NOQA: Imported to register signal handler. import django.db.models.manager # NOQA: Imported to register signal handler.
from django.conf import settings from django.conf import settings
from django.core.exceptions import (ObjectDoesNotExist, from django.core.exceptions import (ObjectDoesNotExist,
@ -1066,7 +1067,7 @@ def model_unpickle(model_id, attrs, factory):
Used to unpickle Model subclasses with deferred fields. Used to unpickle Model subclasses with deferred fields.
""" """
if isinstance(model_id, tuple): if isinstance(model_id, tuple):
model = get_model(*model_id) model = app_cache.get_model(*model_id)
else: else:
# Backwards compat - the model was cached directly in earlier versions. # Backwards compat - the model was cached directly in earlier versions.
model = model_id model = model_id

View File

@ -9,7 +9,7 @@ import warnings
from base64 import b64decode, b64encode from base64 import b64decode, b64encode
from itertools import tee from itertools import tee
from django.apps.cache import get_model from django.apps import app_cache
from django.db import connection from django.db import connection
from django.db.models.query_utils import QueryWrapper from django.db.models.query_utils import QueryWrapper
from django.conf import settings from django.conf import settings
@ -51,7 +51,7 @@ BLANK_CHOICE_DASH = [("", "---------")]
def _load_field(app_label, model_name, field_name): def _load_field(app_label, model_name, field_name):
return get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0] return app_cache.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
class FieldDoesNotExist(Exception): class FieldDoesNotExist(Exception):

View File

@ -1,6 +1,6 @@
import warnings import warnings
from django.apps.cache import cache from django.apps import app_cache
warnings.warn( warnings.warn(
"The utilities in django.db.models.loading are deprecated " "The utilities in django.db.models.loading are deprecated "
@ -12,14 +12,14 @@ __all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models',
# These methods were always module level, so are kept that way for backwards # These methods were always module level, so are kept that way for backwards
# compatibility. # compatibility.
get_apps = cache.get_apps get_apps = app_cache.get_apps
get_app_package = cache.get_app_package get_app_package = app_cache.get_app_package
get_app_path = cache.get_app_path get_app_path = app_cache.get_app_path
get_app_paths = cache.get_app_paths get_app_paths = app_cache.get_app_paths
get_app = cache.get_app get_app = app_cache.get_app
get_app_errors = cache.get_app_errors get_app_errors = app_cache.get_app_errors
get_models = cache.get_models get_models = app_cache.get_models
get_model = cache.get_model get_model = app_cache.get_model
register_models = cache.register_models register_models = app_cache.register_models
load_app = cache.load_app load_app = app_cache.load_app
app_cache_ready = cache.app_cache_ready app_cache_ready = app_cache.app_cache_ready

View File

@ -5,7 +5,7 @@ import re
from bisect import bisect from bisect import bisect
import warnings import warnings
from django.apps.cache import app_cache_ready, cache from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.db.models.fields.related import ManyToManyRel from django.db.models.fields.related import ManyToManyRel
from django.db.models.fields import AutoField, FieldDoesNotExist from django.db.models.fields import AutoField, FieldDoesNotExist
@ -89,7 +89,7 @@ class Options(object):
self.related_fkey_lookups = [] self.related_fkey_lookups = []
# A custom AppCache to use, if you're making a separate model set. # A custom AppCache to use, if you're making a separate model set.
self.app_cache = cache self.app_cache = app_cache
def contribute_to_class(self, cls, name): def contribute_to_class(self, cls, name):
from django.db import connection from django.db import connection
@ -432,7 +432,7 @@ class Options(object):
if hasattr(f, 'related'): if hasattr(f, 'related'):
cache[f.name] = cache[f.attname] = ( cache[f.name] = cache[f.attname] = (
f.related, None if f.model == self.model else f.model, True, False) f.related, None if f.model == self.model else f.model, True, False)
if app_cache_ready(): if app_cache.app_cache_ready():
self._name_map = cache self._name_map = cache
return cache return cache
@ -558,7 +558,7 @@ class Options(object):
and not isinstance(f.rel.to, six.string_types) and not isinstance(f.rel.to, six.string_types)
and self == f.rel.to._meta): and self == f.rel.to._meta):
cache[f.related] = None cache[f.related] = None
if app_cache_ready(): if app_cache.app_cache_ready():
self._related_many_to_many_cache = cache self._related_many_to_many_cache = cache
return cache return cache

View File

@ -1,6 +1,6 @@
from collections import defaultdict from collections import defaultdict
from django.apps.cache import get_model from django.apps import app_cache
from django.dispatch import Signal from django.dispatch import Signal
from django.utils import six from django.utils import six
@ -41,7 +41,7 @@ class ModelSignal(Signal):
"Specified sender must either be a model or a " "Specified sender must either be a model or a "
"model name of the 'app_label.ModelName' form." "model name of the 'app_label.ModelName' form."
) )
sender = get_model(app_label, object_name, only_installed=False) sender = app_cache.get_model(app_label, object_name, only_installed=False)
if sender is None: if sender is None:
reference = (app_label, object_name) reference = (app_label, object_name)
self.unresolved_references[reference].append( self.unresolved_references[reference].append(

View File

@ -282,6 +282,6 @@ class ConnectionRouter(object):
""" """
Return app models allowed to be synchronized on provided db. Return app models allowed to be synchronized on provided db.
""" """
from .models import get_models from django.apps import app_cache
return [model for model in get_models(app, include_auto_created=include_auto_created) return [model for model in app_cache.get_models(app, include_auto_created=include_auto_created)
if self.allow_migrate(db, model)] if self.allow_migrate(db, model)]

View File

@ -9,7 +9,7 @@ import re
import unittest as real_unittest import unittest as real_unittest
import warnings import warnings
from django.db.models import get_app, get_apps from django.apps import app_cache
from django.test import _doctest as doctest from django.test import _doctest as doctest
from django.test import runner from django.test import runner
from django.test.utils import compare_xml, strip_quotes from django.test.utils import compare_xml, strip_quotes
@ -179,7 +179,7 @@ def build_test(label):
# #
# First, look for TestCase instances with a name that matches # First, look for TestCase instances with a name that matches
# #
app_module = get_app(parts[0]) app_module = app_cache.get_app(parts[0])
test_module = get_tests(app_module) test_module = get_tests(app_module)
TestClass = getattr(app_module, parts[1], None) TestClass = getattr(app_module, parts[1], None)
@ -241,10 +241,10 @@ class DjangoTestSuiteRunner(runner.DiscoverRunner):
if '.' in label: if '.' in label:
suite.addTest(build_test(label)) suite.addTest(build_test(label))
else: else:
app = get_app(label) app = app_cache.get_app(label)
suite.addTest(build_suite(app)) suite.addTest(build_suite(app))
else: else:
for app in get_apps(): for app in app_cache.get_apps():
suite.addTest(build_suite(app)) suite.addTest(build_suite(app))
if extra_tests: if extra_tests:

View File

@ -15,7 +15,7 @@ import unittest
from unittest import skipIf # NOQA: Imported here for backward compatibility from unittest import skipIf # NOQA: Imported here for backward compatibility
from unittest.util import safe_repr from unittest.util import safe_repr
from django.apps.cache import cache from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core import mail from django.core import mail
from django.core.exceptions import ValidationError, ImproperlyConfigured from django.core.exceptions import ValidationError, ImproperlyConfigured
@ -725,14 +725,14 @@ class TransactionTestCase(SimpleTestCase):
""" """
super(TransactionTestCase, self)._pre_setup() super(TransactionTestCase, self)._pre_setup()
if self.available_apps is not None: if self.available_apps is not None:
cache.set_available_apps(self.available_apps) app_cache.set_available_apps(self.available_apps)
for db_name in self._databases_names(include_mirrors=False): for db_name in self._databases_names(include_mirrors=False):
flush.Command.emit_post_migrate(verbosity=0, interactive=False, database=db_name) flush.Command.emit_post_migrate(verbosity=0, interactive=False, database=db_name)
try: try:
self._fixture_setup() self._fixture_setup()
except Exception: except Exception:
if self.available_apps is not None: if self.available_apps is not None:
cache.unset_available_apps() app_cache.unset_available_apps()
raise raise
def _databases_names(self, include_mirrors=True): def _databases_names(self, include_mirrors=True):
@ -786,7 +786,7 @@ class TransactionTestCase(SimpleTestCase):
for conn in connections.all(): for conn in connections.all():
conn.close() conn.close()
finally: finally:
cache.unset_available_apps() app_cache.unset_available_apps()
def _fixture_teardown(self): def _fixture_teardown(self):
# Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal # Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal

View File

@ -1,6 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
from django.apps.cache import cache, BaseAppCache from django.apps import app_cache
from django.apps.cache import BaseAppCache
from django.db import models from django.db import models
from django.test import TestCase from django.test import TestCase
@ -16,8 +17,8 @@ class AppCacheTests(TestCase):
""" """
Tests that the models in the models.py file were loaded correctly. Tests that the models in the models.py file were loaded correctly.
""" """
self.assertEqual(cache.get_model("app_cache", "TotallyNormal"), TotallyNormal) self.assertEqual(app_cache.get_model("app_cache", "TotallyNormal"), TotallyNormal)
self.assertEqual(cache.get_model("app_cache", "SoAlternative"), None) self.assertEqual(app_cache.get_model("app_cache", "SoAlternative"), None)
self.assertEqual(new_app_cache.get_model("app_cache", "TotallyNormal"), None) self.assertEqual(new_app_cache.get_model("app_cache", "TotallyNormal"), None)
self.assertEqual(new_app_cache.get_model("app_cache", "SoAlternative"), SoAlternative) self.assertEqual(new_app_cache.get_model("app_cache", "SoAlternative"), SoAlternative)
@ -26,7 +27,7 @@ class AppCacheTests(TestCase):
""" """
Makes a new model at runtime and ensures it goes into the right place. Makes a new model at runtime and ensures it goes into the right place.
""" """
old_models = cache.get_models(cache.get_app("app_cache")) old_models = app_cache.get_models(app_cache.get_app("app_cache"))
# Construct a new model in a new app cache # Construct a new model in a new app cache
body = {} body = {}
new_app_cache = BaseAppCache() new_app_cache = BaseAppCache()
@ -41,6 +42,6 @@ class AppCacheTests(TestCase):
# Make sure it appeared in the right place! # Make sure it appeared in the right place!
self.assertEqual( self.assertEqual(
old_models, old_models,
cache.get_models(cache.get_app("app_cache")), app_cache.get_models(app_cache.get_app("app_cache")),
) )
self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model) self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model)

View File

@ -5,7 +5,8 @@ import os
import sys import sys
from unittest import TestCase from unittest import TestCase
from django.apps.cache import cache, load_app, get_model, get_models, AppCache from django.apps import app_cache
from django.apps.cache import AppCache
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils._os import upath from django.utils._os import upath
@ -19,48 +20,48 @@ class EggLoadingTest(TestCase):
# This test adds dummy applications to the app cache. These # This test adds dummy applications to the app cache. These
# need to be removed in order to prevent bad interactions # need to be removed in order to prevent bad interactions
# with the flush operation in other tests. # with the flush operation in other tests.
self.old_app_models = copy.deepcopy(cache.app_models) self.old_app_models = copy.deepcopy(app_cache.app_models)
def tearDown(self): def tearDown(self):
sys.path = self.old_path sys.path = self.old_path
cache.app_models = self.old_app_models app_cache.app_models = self.old_app_models
def test_egg1(self): def test_egg1(self):
"""Models module can be loaded from an app in an egg""" """Models module can be loaded from an app in an egg"""
egg_name = '%s/modelapp.egg' % self.egg_dir egg_name = '%s/modelapp.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('app_with_models') models = app_cache.load_app('app_with_models')
self.assertFalse(models is None) self.assertFalse(models is None)
def test_egg2(self): def test_egg2(self):
"""Loading an app from an egg that has no models returns no models (and no error)""" """Loading an app from an egg that has no models returns no models (and no error)"""
egg_name = '%s/nomodelapp.egg' % self.egg_dir egg_name = '%s/nomodelapp.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('app_no_models') models = app_cache.load_app('app_no_models')
self.assertTrue(models is None) self.assertTrue(models is None)
def test_egg3(self): def test_egg3(self):
"""Models module can be loaded from an app located under an egg's top-level package""" """Models module can be loaded from an app located under an egg's top-level package"""
egg_name = '%s/omelet.egg' % self.egg_dir egg_name = '%s/omelet.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('omelet.app_with_models') models = app_cache.load_app('omelet.app_with_models')
self.assertFalse(models is None) self.assertFalse(models is None)
def test_egg4(self): def test_egg4(self):
"""Loading an app with no models from under the top-level egg package generates no error""" """Loading an app with no models from under the top-level egg package generates no error"""
egg_name = '%s/omelet.egg' % self.egg_dir egg_name = '%s/omelet.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
models = load_app('omelet.app_no_models') models = app_cache.load_app('omelet.app_no_models')
self.assertTrue(models is None) self.assertTrue(models is None)
def test_egg5(self): def test_egg5(self):
"""Loading an app from an egg that has an import error in its models module raises that error""" """Loading an app from an egg that has an import error in its models module raises that error"""
egg_name = '%s/brokenapp.egg' % self.egg_dir egg_name = '%s/brokenapp.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
self.assertRaises(ImportError, load_app, 'broken_app') self.assertRaises(ImportError, app_cache.load_app, 'broken_app')
raised = None raised = None
try: try:
load_app('broken_app') app_cache.load_app('broken_app')
except ImportError as e: except ImportError as e:
raised = e raised = e
@ -81,8 +82,8 @@ class EggLoadingTest(TestCase):
a.loaded = False a.loaded = False
try: try:
with override_settings(INSTALLED_APPS=('notexists',)): with override_settings(INSTALLED_APPS=('notexists',)):
self.assertRaises(ImportError, get_model, 'notexists', 'nomodel', seed_cache=True) self.assertRaises(ImportError, app_cache.get_model, 'notexists', 'nomodel', seed_cache=True)
self.assertRaises(ImportError, get_model, 'notexists', 'nomodel', seed_cache=True) self.assertRaises(ImportError, app_cache.get_model, 'notexists', 'nomodel', seed_cache=True)
finally: finally:
a.loaded = True a.loaded = True
@ -94,26 +95,26 @@ class GetModelsTest(TestCase):
def test_get_model_only_returns_installed_models(self): def test_get_model_only_returns_installed_models(self):
self.assertEqual( self.assertEqual(
get_model("not_installed", "NotInstalledModel"), None) app_cache.get_model("not_installed", "NotInstalledModel"), None)
def test_get_model_with_not_installed(self): def test_get_model_with_not_installed(self):
self.assertEqual( self.assertEqual(
get_model( app_cache.get_model(
"not_installed", "NotInstalledModel", only_installed=False), "not_installed", "NotInstalledModel", only_installed=False),
self.not_installed_module.NotInstalledModel) self.not_installed_module.NotInstalledModel)
def test_get_models_only_returns_installed_models(self): def test_get_models_only_returns_installed_models(self):
self.assertFalse( self.assertFalse(
"NotInstalledModel" in "NotInstalledModel" in
[m.__name__ for m in get_models()]) [m.__name__ for m in app_cache.get_models()])
def test_get_models_with_app_label_only_returns_installed_models(self): def test_get_models_with_app_label_only_returns_installed_models(self):
self.assertEqual(get_models(self.not_installed_module), []) self.assertEqual(app_cache.get_models(self.not_installed_module), [])
def test_get_models_with_not_installed(self): def test_get_models_with_not_installed(self):
self.assertTrue( self.assertTrue(
"NotInstalledModel" in [ "NotInstalledModel" in [
m.__name__ for m in get_models(only_installed=False)]) m.__name__ for m in app_cache.get_models(only_installed=False)])
class NotInstalledModelsTest(TestCase): class NotInstalledModelsTest(TestCase):

View File

@ -1,9 +1,10 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from django.apps import app_cache
from django.core.management.color import no_style from django.core.management.color import no_style
from django.core.management.sql import (sql_create, sql_delete, sql_indexes, from django.core.management.sql import (sql_create, sql_delete, sql_indexes,
sql_destroy_indexes, sql_all) sql_destroy_indexes, sql_all)
from django.db import connections, DEFAULT_DB_ALIAS, models, router from django.db import connections, DEFAULT_DB_ALIAS, router
from django.test import TestCase from django.test import TestCase
from django.utils import six from django.utils import six
@ -16,7 +17,7 @@ class SQLCommandsTestCase(TestCase):
return len([o for o in output if o.startswith(cmd)]) return len([o for o in output if o.startswith(cmd)])
def test_sql_create(self): def test_sql_create(self):
app = models.get_app('commands_sql') app = app_cache.get_app('commands_sql')
output = sql_create(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_create(app, no_style(), connections[DEFAULT_DB_ALIAS])
create_tables = [o for o in output if o.startswith('CREATE TABLE')] create_tables = [o for o in output if o.startswith('CREATE TABLE')]
self.assertEqual(len(create_tables), 3) self.assertEqual(len(create_tables), 3)
@ -25,7 +26,7 @@ class SQLCommandsTestCase(TestCase):
six.assertRegex(self, sql, r'^create table .commands_sql_book.*') six.assertRegex(self, sql, r'^create table .commands_sql_book.*')
def test_sql_delete(self): def test_sql_delete(self):
app = models.get_app('commands_sql') app = app_cache.get_app('commands_sql')
output = sql_delete(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_delete(app, no_style(), connections[DEFAULT_DB_ALIAS])
drop_tables = [o for o in output if o.startswith('DROP TABLE')] drop_tables = [o for o in output if o.startswith('DROP TABLE')]
self.assertEqual(len(drop_tables), 3) self.assertEqual(len(drop_tables), 3)
@ -34,19 +35,19 @@ class SQLCommandsTestCase(TestCase):
six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*') six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*')
def test_sql_indexes(self): def test_sql_indexes(self):
app = models.get_app('commands_sql') app = app_cache.get_app('commands_sql')
output = sql_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS])
# PostgreSQL creates one additional index for CharField # PostgreSQL creates one additional index for CharField
self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4]) self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4])
def test_sql_destroy_indexes(self): def test_sql_destroy_indexes(self):
app = models.get_app('commands_sql') app = app_cache.get_app('commands_sql')
output = sql_destroy_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_destroy_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS])
# PostgreSQL creates one additional index for CharField # PostgreSQL creates one additional index for CharField
self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4]) self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4])
def test_sql_all(self): def test_sql_all(self):
app = models.get_app('commands_sql') app = app_cache.get_app('commands_sql')
output = sql_all(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_all(app, no_style(), connections[DEFAULT_DB_ALIAS])
self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3) self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3)
@ -68,7 +69,7 @@ class SQLCommandsRouterTestCase(TestCase):
router.routers = self._old_routers router.routers = self._old_routers
def test_router_honored(self): def test_router_honored(self):
app = models.get_app('commands_sql') app = app_cache.get_app('commands_sql')
for sql_command in (sql_all, sql_create, sql_delete, sql_indexes, sql_destroy_indexes): for sql_command in (sql_all, sql_create, sql_delete, sql_indexes, sql_destroy_indexes):
output = sql_command(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_command(app, no_style(), connections[DEFAULT_DB_ALIAS])
self.assertEqual(len(output), 0, self.assertEqual(len(output), 0,

View File

@ -2,7 +2,7 @@ from __future__ import unicode_literals
from operator import attrgetter from operator import attrgetter
from django.apps.cache import cache from django.apps import app_cache
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.backends.db import SessionStore from django.contrib.sessions.backends.db import SessionStore
from django.db.models import Count from django.db.models import Count
@ -103,7 +103,7 @@ class DeferRegressionTest(TestCase):
klasses = set( klasses = set(
map( map(
attrgetter("__name__"), attrgetter("__name__"),
cache.get_models(cache.get_app("defer_regress")) app_cache.get_models(app_cache.get_app("defer_regress"))
) )
) )
self.assertIn("Child", klasses) self.assertIn("Child", klasses)
@ -111,13 +111,13 @@ class DeferRegressionTest(TestCase):
self.assertNotIn("Child_Deferred_value", klasses) self.assertNotIn("Child_Deferred_value", klasses)
self.assertNotIn("Item_Deferred_name", klasses) self.assertNotIn("Item_Deferred_name", klasses)
self.assertFalse(any( self.assertFalse(any(
k._deferred for k in cache.get_models(cache.get_app("defer_regress")))) k._deferred for k in app_cache.get_models(app_cache.get_app("defer_regress"))))
klasses_with_deferred = set( klasses_with_deferred = set(
map( map(
attrgetter("__name__"), attrgetter("__name__"),
cache.get_models( app_cache.get_models(
cache.get_app("defer_regress"), include_deferred=True app_cache.get_app("defer_regress"), include_deferred=True
), ),
) )
) )
@ -126,8 +126,8 @@ class DeferRegressionTest(TestCase):
self.assertIn("Child_Deferred_value", klasses_with_deferred) self.assertIn("Child_Deferred_value", klasses_with_deferred)
self.assertIn("Item_Deferred_name", klasses_with_deferred) self.assertIn("Item_Deferred_name", klasses_with_deferred)
self.assertTrue(any( self.assertTrue(any(
k._deferred for k in cache.get_models( k._deferred for k in app_cache.get_models(
cache.get_app("defer_regress"), include_deferred=True)) app_cache.get_app("defer_regress"), include_deferred=True))
) )
@override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer') @override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer')

View File

@ -1,4 +1,4 @@
from django.apps.cache import get_app from django.apps import app_cache
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
@ -33,4 +33,4 @@ class NoModelTests(TestCase):
def test_no_models(self): def test_no_models(self):
with six.assertRaisesRegex(self, ImproperlyConfigured, with six.assertRaisesRegex(self, ImproperlyConfigured,
'App with label no_models is missing a models.py module.'): 'App with label no_models is missing a models.py module.'):
get_app('no_models') app_cache.get_app('no_models')

View File

@ -2,7 +2,7 @@ import copy
import sys import sys
import unittest import unittest
from django.apps.cache import cache, load_app from django.apps import app_cache
from django.core.management.validation import get_validation_errors from django.core.management.validation import get_validation_errors
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils.six import StringIO from django.utils.six import StringIO
@ -22,11 +22,11 @@ class InvalidModelTestCase(unittest.TestCase):
# This test adds dummy applications to the app cache. These # This test adds dummy applications to the app cache. These
# need to be removed in order to prevent bad interactions # need to be removed in order to prevent bad interactions
# with the flush operation in other tests. # with the flush operation in other tests.
self.old_app_models = copy.deepcopy(cache.app_models) self.old_app_models = copy.deepcopy(app_cache.app_models)
def tearDown(self): def tearDown(self):
cache.app_models = self.old_app_models app_cache.app_models = self.old_app_models
cache._get_models_cache = {} app_cache._get_models_cache = {}
sys.stdout = self.old_stdout sys.stdout = self.old_stdout
# Technically, this isn't an override -- TEST_SWAPPED_MODEL must be # Technically, this isn't an override -- TEST_SWAPPED_MODEL must be
@ -40,7 +40,7 @@ class InvalidModelTestCase(unittest.TestCase):
) )
def test_invalid_models(self): def test_invalid_models(self):
try: try:
module = load_app("invalid_models.invalid_models") module = app_cache.load_app("invalid_models.invalid_models")
except Exception: except Exception:
self.fail('Unable to load invalid model module') self.fail('Unable to load invalid model module')

View File

@ -1,7 +1,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import copy import copy
from django.apps.cache import cache from django.apps import app_cache
from django.db import models from django.db import models
from django.template import Context, Template from django.template import Context, Template
from django.test import TestCase from django.test import TestCase
@ -114,7 +114,7 @@ class ManagersRegressionTests(TestCase):
# This test adds dummy models to the app cache. These # This test adds dummy models to the app cache. These
# need to be removed in order to prevent bad interactions # need to be removed in order to prevent bad interactions
# with the flush operation in other tests. # with the flush operation in other tests.
old_app_models = copy.deepcopy(cache.app_models) old_app_models = copy.deepcopy(app_cache.app_models)
class SwappableModel(models.Model): class SwappableModel(models.Model):
class Meta: class Meta:
@ -129,7 +129,7 @@ class ManagersRegressionTests(TestCase):
self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'")
finally: finally:
cache.app_models = old_app_models app_cache.app_models = old_app_models
@override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent')
def test_custom_swappable_manager(self): def test_custom_swappable_manager(self):
@ -137,7 +137,7 @@ class ManagersRegressionTests(TestCase):
# This test adds dummy models to the app cache. These # This test adds dummy models to the app cache. These
# need to be removed in order to prevent bad interactions # need to be removed in order to prevent bad interactions
# with the flush operation in other tests. # with the flush operation in other tests.
old_app_models = copy.deepcopy(cache.app_models) old_app_models = copy.deepcopy(app_cache.app_models)
class SwappableModel(models.Model): class SwappableModel(models.Model):
@ -156,7 +156,7 @@ class ManagersRegressionTests(TestCase):
self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'")
finally: finally:
cache.app_models = old_app_models app_cache.app_models = old_app_models
@override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent')
def test_explicit_swappable_manager(self): def test_explicit_swappable_manager(self):
@ -164,7 +164,7 @@ class ManagersRegressionTests(TestCase):
# This test adds dummy models to the app cache. These # This test adds dummy models to the app cache. These
# need to be removed in order to prevent bad interactions # need to be removed in order to prevent bad interactions
# with the flush operation in other tests. # with the flush operation in other tests.
old_app_models = copy.deepcopy(cache.app_models) old_app_models = copy.deepcopy(app_cache.app_models)
class SwappableModel(models.Model): class SwappableModel(models.Model):
@ -183,7 +183,7 @@ class ManagersRegressionTests(TestCase):
self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'")
finally: finally:
cache.app_models = old_app_models app_cache.app_models = old_app_models
def test_regress_3871(self): def test_regress_3871(self):
related = RelatedModel.objects.create() related = RelatedModel.objects.create()

View File

@ -6,7 +6,7 @@ import copy
import os import os
import shutil import shutil
from django.apps.cache import cache from django.apps import app_cache
from django.core.management import call_command, CommandError from django.core.management import call_command, CommandError
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six from django.utils import six
@ -132,11 +132,11 @@ class MakeMigrationsTests(MigrationTestBase):
self.test_dir = os.path.abspath(os.path.dirname(upath(__file__))) self.test_dir = os.path.abspath(os.path.dirname(upath(__file__)))
self.migration_dir = os.path.join(self.test_dir, 'migrations_%d' % self.creation_counter) self.migration_dir = os.path.join(self.test_dir, 'migrations_%d' % self.creation_counter)
self.migration_pkg = "migrations.migrations_%d" % self.creation_counter self.migration_pkg = "migrations.migrations_%d" % self.creation_counter
self._old_app_models = copy.deepcopy(cache.app_models) self._old_app_models = copy.deepcopy(app_cache.app_models)
def tearDown(self): def tearDown(self):
cache.app_models = self._old_app_models app_cache.app_models = self._old_app_models
cache._get_models_cache = {} app_cache._get_models_cache = {}
os.chdir(self.test_dir) os.chdir(self.test_dir)
try: try:
@ -152,7 +152,7 @@ class MakeMigrationsTests(MigrationTestBase):
def test_files_content(self): def test_files_content(self):
self.assertTableNotExists("migrations_unicodemodel") self.assertTableNotExists("migrations_unicodemodel")
cache.register_models('migrations', UnicodeModel) app_cache.register_models('migrations', UnicodeModel)
with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}): with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}):
call_command("makemigrations", "migrations", verbosity=0) call_command("makemigrations", "migrations", verbosity=0)
@ -188,7 +188,7 @@ class MakeMigrationsTests(MigrationTestBase):
def test_failing_migration(self): def test_failing_migration(self):
#21280 - If a migration fails to serialize, it shouldn't generate an empty file. #21280 - If a migration fails to serialize, it shouldn't generate an empty file.
cache.register_models('migrations', UnserializableModel) app_cache.register_models('migrations', UnserializableModel)
with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'): with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'):
with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}): with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}):

View File

@ -1,4 +1,5 @@
import unittest import unittest
from django.apps import app_cache
from django.db import connection, models, migrations, router from django.db import connection, models, migrations, router
from django.db.models.fields import NOT_PROVIDED from django.db.models.fields import NOT_PROVIDED
from django.db.transaction import atomic from django.db.transaction import atomic
@ -203,8 +204,8 @@ class OperationTests(MigrationTestBase):
self.assertColumnNotExists("test_adflmm_pony", "stables") self.assertColumnNotExists("test_adflmm_pony", "stables")
# Make sure the M2M field actually works # Make sure the M2M field actually works
with atomic(): with atomic():
app_cache = new_state.render() new_app_cache = new_state.render()
Pony = app_cache.get_model("test_adflmm", "Pony") Pony = new_app_cache.get_model("test_adflmm", "Pony")
p = Pony.objects.create(pink=False, weight=4.55) p = Pony.objects.create(pink=False, weight=4.55)
p.stables.create() p.stables.create()
self.assertEqual(p.stables.count(), 1) self.assertEqual(p.stables.count(), 1)

View File

@ -5,7 +5,7 @@ from __future__ import unicode_literals
import datetime import datetime
import os import os
from django.apps.cache import cache from django.apps import app_cache
from django.core.validators import RegexValidator, EmailValidator from django.core.validators import RegexValidator, EmailValidator
from django.db import models, migrations from django.db import models, migrations
from django.db.migrations.writer import MigrationWriter from django.db.migrations.writer import MigrationWriter
@ -124,7 +124,7 @@ class WriterTests(TestCase):
with override_settings(INSTALLED_APPS=test_apps): with override_settings(INSTALLED_APPS=test_apps):
for app in test_apps: for app in test_apps:
cache.load_app(app) app_cache.load_app(app)
migration = migrations.Migration('0001_initial', app.split('.')[-1]) migration = migrations.Migration('0001_initial', app.split('.')[-1])
expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py'])) expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py']))
writer = MigrationWriter(migration) writer = MigrationWriter(migration)

View File

@ -3,7 +3,7 @@ from __future__ import unicode_literals
import os import os
import sys import sys
from django.apps.cache import cache, load_app from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.core.management import call_command from django.core.management import call_command
from django.test import TestCase, TransactionTestCase from django.test import TestCase, TransactionTestCase
@ -28,21 +28,21 @@ class ProxyModelInheritanceTests(TransactionTestCase):
self.old_sys_path = sys.path[:] self.old_sys_path = sys.path[:]
sys.path.append(os.path.dirname(os.path.abspath(upath(__file__)))) sys.path.append(os.path.dirname(os.path.abspath(upath(__file__))))
for app in settings.INSTALLED_APPS: for app in settings.INSTALLED_APPS:
load_app(app) app_cache.load_app(app)
def tearDown(self): def tearDown(self):
sys.path = self.old_sys_path sys.path = self.old_sys_path
del cache.app_labels['app1'] del app_cache.app_labels['app1']
del cache.app_labels['app2'] del app_cache.app_labels['app2']
del cache.app_models['app1'] del app_cache.app_models['app1']
del cache.app_models['app2'] del app_cache.app_models['app2']
def test_table_exists(self): def test_table_exists(self):
try: try:
cache.set_available_apps(settings.INSTALLED_APPS) app_cache.set_available_apps(settings.INSTALLED_APPS)
call_command('migrate', verbosity=0) call_command('migrate', verbosity=0)
finally: finally:
cache.unset_available_apps() app_cache.unset_available_apps()
from .app1.models import ProxyModel from .app1.models import ProxyModel
from .app2.models import NiceModel from .app2.models import NiceModel
self.assertEqual(NiceModel.objects.all().count(), 0) self.assertEqual(NiceModel.objects.all().count(), 0)

View File

@ -1,7 +1,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import copy import copy
from django.apps.cache import cache from django.apps import app_cache
from django.contrib import admin from django.contrib import admin
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core import management from django.core import management
@ -159,7 +159,7 @@ class ProxyModelTests(TestCase):
# This test adds dummy applications to the app cache. These # This test adds dummy applications to the app cache. These
# need to be removed in order to prevent bad interactions # need to be removed in order to prevent bad interactions
# with the flush operation in other tests. # with the flush operation in other tests.
old_app_models = copy.deepcopy(cache.app_models) old_app_models = copy.deepcopy(app_cache.app_models)
class SwappableModel(models.Model): class SwappableModel(models.Model):
@ -176,7 +176,7 @@ class ProxyModelTests(TestCase):
class Meta: class Meta:
proxy = True proxy = True
finally: finally:
cache.app_models = old_app_models app_cache.app_models = old_app_models
def test_myperson_manager(self): def test_myperson_manager(self):
Person.objects.create(name="fred") Person.objects.create(name="fred")

View File

@ -80,13 +80,13 @@ def get_test_modules():
def get_installed(): def get_installed():
from django.apps.cache import get_apps from django.apps import app_cache
return [app.__name__.rsplit('.', 1)[0] for app in get_apps()] return [app.__name__.rsplit('.', 1)[0] for app in app_cache.get_apps()]
def setup(verbosity, test_labels): def setup(verbosity, test_labels):
import django import django
from django.apps.cache import get_apps, load_app from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.test import TransactionTestCase, TestCase from django.test import TransactionTestCase, TestCase
@ -128,7 +128,7 @@ def setup(verbosity, test_labels):
# Load all the ALWAYS_INSTALLED_APPS. # Load all the ALWAYS_INSTALLED_APPS.
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', DeprecationWarning) warnings.filterwarnings('ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', DeprecationWarning)
get_apps() app_cache.get_apps()
# Load all the test model apps. # Load all the test model apps.
test_modules = get_test_modules() test_modules = get_test_modules()
@ -164,7 +164,7 @@ def setup(verbosity, test_labels):
if module_found_in_labels: if module_found_in_labels:
if verbosity >= 2: if verbosity >= 2:
print("Importing application %s" % module_name) print("Importing application %s" % module_name)
mod = load_app(module_label) mod = app_cache.load_app(module_label)
if mod: if mod:
if module_label not in settings.INSTALLED_APPS: if module_label not in settings.INSTALLED_APPS:
settings.INSTALLED_APPS.append(module_label) settings.INSTALLED_APPS.append(module_label)

View File

@ -2,7 +2,7 @@ from __future__ import unicode_literals
from django.utils.six import StringIO from django.utils.six import StringIO
from django.apps.cache import cache from django.apps import app_cache
from django.contrib.auth.models import Permission from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core import management from django.core import management
@ -23,12 +23,12 @@ class SwappableModelTests(TestCase):
def setUp(self): def setUp(self):
# This test modifies the installed apps, so we need to make sure # This test modifies the installed apps, so we need to make sure
# we're not dealing with a cached app list. # we're not dealing with a cached app list.
cache._get_models_cache.clear() app_cache._get_models_cache.clear()
def tearDown(self): def tearDown(self):
# By fiddling with swappable models, we alter the installed models # By fiddling with swappable models, we alter the installed models
# cache, so flush it to make sure there are no side effects. # cache, so flush it to make sure there are no side effects.
cache._get_models_cache.clear() app_cache._get_models_cache.clear()
@override_settings(TEST_ARTICLE_MODEL='swappable_models.AlternateArticle') @override_settings(TEST_ARTICLE_MODEL='swappable_models.AlternateArticle')
def test_generated_data(self): def test_generated_data(self):

View File

@ -2,7 +2,7 @@ from __future__ import unicode_literals
import copy import copy
from django.apps.cache import cache from django.apps import app_cache
from django.conf import settings from django.conf import settings
from django.db import connection from django.db import connection
from django.core.management.color import no_style from django.core.management.color import no_style
@ -28,7 +28,7 @@ class TablespacesTests(TestCase):
def setUp(self): def setUp(self):
# The unmanaged models need to be removed after the test in order to # The unmanaged models need to be removed after the test in order to
# prevent bad interactions with the flush operation in other tests. # prevent bad interactions with the flush operation in other tests.
self.old_app_models = copy.deepcopy(cache.app_models) self.old_app_models = copy.deepcopy(app_cache.app_models)
for model in Article, Authors, Reviewers, Scientist: for model in Article, Authors, Reviewers, Scientist:
model._meta.managed = True model._meta.managed = True
@ -37,8 +37,8 @@ class TablespacesTests(TestCase):
for model in Article, Authors, Reviewers, Scientist: for model in Article, Authors, Reviewers, Scientist:
model._meta.managed = False model._meta.managed = False
cache.app_models = self.old_app_models app_cache.app_models = self.old_app_models
cache._get_models_cache = {} app_cache._get_models_cache = {}
def assertNumContains(self, haystack, needle, count): def assertNumContains(self, haystack, needle, count):
real_count = haystack.count(needle) real_count = haystack.count(needle)

View File

@ -1,6 +1,6 @@
import unittest import unittest
from django.db.models import get_app from django.apps import app_cache
from django.test.utils import IgnoreAllDeprecationWarningsMixin from django.test.utils import IgnoreAllDeprecationWarningsMixin
@ -20,7 +20,7 @@ class SuiteOverrideTest(IgnoreAllDeprecationWarningsMixin, unittest.TestCase):
""" """
from django.test.simple import build_suite from django.test.simple import build_suite
app = get_app("test_suite_override") app = app_cache.get_app("test_suite_override")
suite = build_suite(app) suite = build_suite(app)
self.assertEqual(suite.countTestCases(), 1) self.assertEqual(suite.countTestCases(), 1)