Renamed AppCache to Apps.
Also renamed app_cache to apps and "app cache" to "app registry". Deprecated AppCache.app_cache_ready() in favor of Apps.ready().
This commit is contained in:
parent
e9e522a8e7
commit
1716b7ce5a
|
@ -1,2 +1,2 @@
|
||||||
from .base import AppConfig # NOQA
|
from .base import AppConfig # NOQA
|
||||||
from .cache import app_cache # NOQA
|
from .registry import apps # NOQA
|
||||||
|
|
|
@ -97,8 +97,8 @@ class AppConfig(object):
|
||||||
|
|
||||||
def import_models(self, all_models):
|
def import_models(self, all_models):
|
||||||
# Dictionary of models for this app, stored in the 'all_models'
|
# Dictionary of models for this app, stored in the 'all_models'
|
||||||
# attribute of the AppCache this AppConfig is attached to. Injected as
|
# attribute of the Apps this AppConfig is attached to. Injected as a
|
||||||
# a parameter because it may get populated before this method has run.
|
# parameter because it may get populated before this method has run.
|
||||||
self.models = all_models
|
self.models = all_models
|
||||||
|
|
||||||
if module_has_submodule(self.app_module, MODELS_MODULE_NAME):
|
if module_has_submodule(self.app_module, MODELS_MODULE_NAME):
|
||||||
|
|
|
@ -14,25 +14,26 @@ from django.utils._os import upath
|
||||||
from .base import AppConfig
|
from .base import AppConfig
|
||||||
|
|
||||||
|
|
||||||
class AppCache(object):
|
class Apps(object):
|
||||||
"""
|
"""
|
||||||
A cache that stores installed applications and their models. Used to
|
A registry that stores the configuration of installed applications.
|
||||||
provide reverse-relations and for app introspection.
|
|
||||||
|
It also keeps track of models eg. to provide reverse-relations.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, master=False):
|
def __init__(self, master=False):
|
||||||
# Only one master of the app-cache may exist at a given time, and it
|
# Only one master registry may exist at a given time, and it shall be
|
||||||
# shall be the app_cache variable defined at the end of this module.
|
# the apps variable defined at the end of this module.
|
||||||
if master and hasattr(sys.modules[__name__], 'app_cache'):
|
if master and hasattr(sys.modules[__name__], 'apps'):
|
||||||
raise RuntimeError("You may create only one master app cache.")
|
raise RuntimeError("You may create only one master registry.")
|
||||||
|
|
||||||
# When master is set to False, the app cache isn't populated from
|
# When master is set to False, the registry isn't populated from
|
||||||
# INSTALLED_APPS and ignores the only_installed arguments to
|
# INSTALLED_APPS and ignores the only_installed arguments to
|
||||||
# get_model[s].
|
# get_model[s].
|
||||||
self.master = master
|
self.master = master
|
||||||
|
|
||||||
# Mapping of app labels => model names => model classes. Used to
|
# Mapping of app labels => model names => model classes. Used to
|
||||||
# register models before the app cache is populated and also for
|
# register models before the registry is populated and also for
|
||||||
# applications that aren't installed.
|
# applications that aren't installed.
|
||||||
self.all_models = defaultdict(OrderedDict)
|
self.all_models = defaultdict(OrderedDict)
|
||||||
|
|
||||||
|
@ -43,7 +44,7 @@ class AppCache(object):
|
||||||
# set_available_apps and set_installed_apps.
|
# set_available_apps and set_installed_apps.
|
||||||
self.stored_app_configs = []
|
self.stored_app_configs = []
|
||||||
|
|
||||||
# Internal flags used when populating the master cache.
|
# Internal flags used when populating the master registry.
|
||||||
self._apps_loaded = not self.master
|
self._apps_loaded = not self.master
|
||||||
self._models_loaded = not self.master
|
self._models_loaded = not self.master
|
||||||
|
|
||||||
|
@ -133,9 +134,9 @@ class AppCache(object):
|
||||||
self.get_models.cache_clear()
|
self.get_models.cache_clear()
|
||||||
self._models_loaded = True
|
self._models_loaded = True
|
||||||
|
|
||||||
def app_cache_ready(self):
|
def ready(self):
|
||||||
"""
|
"""
|
||||||
Returns true if the model cache is fully populated.
|
Returns True if the registry is fully populated.
|
||||||
|
|
||||||
Useful for code that wants to cache the results of get_models() for
|
Useful for code that wants to cache the results of get_models() for
|
||||||
themselves once it is safe to do so.
|
themselves once it is safe to do so.
|
||||||
|
@ -200,7 +201,7 @@ class AppCache(object):
|
||||||
By default, models that aren't part of installed apps will *not*
|
By default, models that aren't part of installed apps will *not*
|
||||||
be included in the list of models. However, if you specify
|
be included in the list of models. However, if you specify
|
||||||
only_installed=False, they will be. If you're using a non-default
|
only_installed=False, they will be. If you're using a non-default
|
||||||
AppCache, this argument does nothing - all models will be included.
|
Apps, this argument does nothing - all models will be included.
|
||||||
|
|
||||||
By default, models that have been swapped out will *not* be
|
By default, models that have been swapped out will *not* be
|
||||||
included in the list of models. However, if you specify
|
included in the list of models. However, if you specify
|
||||||
|
@ -272,11 +273,11 @@ class AppCache(object):
|
||||||
|
|
||||||
def has_app(self, app_name):
|
def has_app(self, app_name):
|
||||||
"""
|
"""
|
||||||
Checks whether an application with this name exists in the app cache.
|
Checks whether an application with this name exists in the registry.
|
||||||
|
|
||||||
app_name is the full name of the app eg. 'django.contrib.admin'.
|
app_name is the full name of the app eg. 'django.contrib.admin'.
|
||||||
|
|
||||||
It's safe to call this method at import time, even while the app cache
|
It's safe to call this method at import time, even while the registry
|
||||||
is being populated. It returns None for apps that aren't loaded yet.
|
is being populated. It returns None for apps that aren't loaded yet.
|
||||||
"""
|
"""
|
||||||
app_config = self.app_configs.get(app_name.rpartition(".")[2])
|
app_config = self.app_configs.get(app_name.rpartition(".")[2])
|
||||||
|
@ -286,7 +287,7 @@ class AppCache(object):
|
||||||
"""
|
"""
|
||||||
Returns the model class if one is registered and None otherwise.
|
Returns the model class if one is registered and None otherwise.
|
||||||
|
|
||||||
It's safe to call this method at import time, even while the app cache
|
It's safe to call this method at import time, even while the registry
|
||||||
is being populated. It returns None for models that aren't loaded yet.
|
is being populated. It returns None for models that aren't loaded yet.
|
||||||
"""
|
"""
|
||||||
return self.all_models[app_label].get(model_name.lower())
|
return self.all_models[app_label].get(model_name.lower())
|
||||||
|
@ -371,6 +372,12 @@ class AppCache(object):
|
||||||
self.get_models.cache_clear()
|
self.get_models.cache_clear()
|
||||||
return app_config.models_module
|
return app_config.models_module
|
||||||
|
|
||||||
|
def app_cache_ready(self):
|
||||||
|
warnings.warn(
|
||||||
|
"app_cache_ready() is deprecated.",
|
||||||
|
PendingDeprecationWarning, stacklevel=2)
|
||||||
|
return self.ready()
|
||||||
|
|
||||||
def get_app(self, app_label):
|
def get_app(self, app_label):
|
||||||
"""
|
"""
|
||||||
Returns the module containing the models for the given app_label.
|
Returns the module containing the models for the given app_label.
|
||||||
|
@ -446,4 +453,4 @@ class AppCache(object):
|
||||||
self.register_model(app_label, model)
|
self.register_model(app_label, model)
|
||||||
|
|
||||||
|
|
||||||
app_cache = AppCache(master=True)
|
apps = Apps(master=True)
|
|
@ -6,7 +6,7 @@ from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME
|
||||||
from django.contrib.contenttypes import views as contenttype_views
|
from django.contrib.contenttypes import views as contenttype_views
|
||||||
from django.views.decorators.csrf import csrf_protect
|
from django.views.decorators.csrf import csrf_protect
|
||||||
from django.db.models.base import ModelBase
|
from django.db.models.base import ModelBase
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
|
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
|
||||||
from django.core.urlresolvers import reverse, NoReverseMatch
|
from django.core.urlresolvers import reverse, NoReverseMatch
|
||||||
from django.template.response import TemplateResponse
|
from django.template.response import TemplateResponse
|
||||||
|
@ -160,11 +160,11 @@ class AdminSite(object):
|
||||||
The default implementation checks that admin and contenttypes apps are
|
The default implementation checks that admin and contenttypes apps are
|
||||||
installed, as well as the auth context processor.
|
installed, as well as the auth context processor.
|
||||||
"""
|
"""
|
||||||
app_cache.populate_apps()
|
apps.populate_apps()
|
||||||
if not app_cache.has_app('django.contrib.admin'):
|
if not apps.has_app('django.contrib.admin'):
|
||||||
raise ImproperlyConfigured("Put 'django.contrib.admin' in your "
|
raise ImproperlyConfigured("Put 'django.contrib.admin' in your "
|
||||||
"INSTALLED_APPS setting in order to use the admin application.")
|
"INSTALLED_APPS setting in order to use the admin application.")
|
||||||
if not app_cache.has_app('django.contrib.contenttypes'):
|
if not apps.has_app('django.contrib.contenttypes'):
|
||||||
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
|
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
|
||||||
"your INSTALLED_APPS setting in order to use the admin application.")
|
"your INSTALLED_APPS setting in order to use the admin application.")
|
||||||
if 'django.contrib.auth.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS:
|
if 'django.contrib.auth.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS:
|
||||||
|
@ -381,7 +381,7 @@ class AdminSite(object):
|
||||||
app_dict[app_label]['models'].append(model_dict)
|
app_dict[app_label]['models'].append(model_dict)
|
||||||
else:
|
else:
|
||||||
app_dict[app_label] = {
|
app_dict[app_label] = {
|
||||||
'name': app_cache.get_app_config(app_label).verbose_name,
|
'name': apps.get_app_config(app_label).verbose_name,
|
||||||
'app_label': app_label,
|
'app_label': app_label,
|
||||||
'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name),
|
'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name),
|
||||||
'has_module_perms': has_module_perms,
|
'has_module_perms': has_module_perms,
|
||||||
|
@ -408,7 +408,7 @@ class AdminSite(object):
|
||||||
|
|
||||||
def app_index(self, request, app_label, extra_context=None):
|
def app_index(self, request, app_label, extra_context=None):
|
||||||
user = request.user
|
user = request.user
|
||||||
app_name = app_cache.get_app_config(app_label).verbose_name
|
app_name = apps.get_app_config(app_label).verbose_name
|
||||||
has_module_perms = user.has_module_perms(app_label)
|
has_module_perms = user.has_module_perms(app_label)
|
||||||
if not has_module_perms:
|
if not has_module_perms:
|
||||||
raise PermissionDenied
|
raise PermissionDenied
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.template import Library
|
from django.template import Library
|
||||||
|
|
||||||
register = Library()
|
register = Library()
|
||||||
|
|
||||||
if app_cache.has_app('django.contrib.staticfiles'):
|
if apps.has_app('django.contrib.staticfiles'):
|
||||||
from django.contrib.staticfiles.templatetags.staticfiles import static
|
from django.contrib.staticfiles.templatetags.staticfiles import static
|
||||||
else:
|
else:
|
||||||
from django.templatetags.static import static
|
from django.templatetags.static import static
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -16,9 +16,9 @@ __all__ = ['BaseValidator', 'InlineValidator']
|
||||||
|
|
||||||
class BaseValidator(object):
|
class BaseValidator(object):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
# Before we can introspect models, they need the app cache to be fully
|
# Before we can introspect models, they need the app registry to be
|
||||||
# loaded so that inter-relations are set up correctly.
|
# fully loaded so that inter-relations are set up correctly.
|
||||||
app_cache.populate_models()
|
apps.populate_models()
|
||||||
|
|
||||||
def validate(self, cls, model):
|
def validate(self, cls, model):
|
||||||
for m in dir(self):
|
for m in dir(self):
|
||||||
|
|
|
@ -5,7 +5,7 @@ import re
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django import template
|
from django import template
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -174,7 +174,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 app_cache.get_models()]
|
m_list = [m._meta for m in apps.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)
|
||||||
|
|
||||||
|
@ -185,10 +185,10 @@ 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_cache.get_app_config(self.kwargs['app_label'])
|
apps.get_app_config(self.kwargs['app_label'])
|
||||||
except LookupError:
|
except LookupError:
|
||||||
raise Http404(_("App %(app_label)r not found") % self.kwargs)
|
raise Http404(_("App %(app_label)r not found") % self.kwargs)
|
||||||
model = app_cache.get_model(self.kwargs['app_label'], self.kwargs['model_name'])
|
model = apps.get_model(self.kwargs['app_label'], self.kwargs['model_name'])
|
||||||
if model is None:
|
if model is None:
|
||||||
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs)
|
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs)
|
||||||
|
|
||||||
|
|
|
@ -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.apps import app_cache
|
from django.apps import apps
|
||||||
|
|
||||||
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 = app_cache.get_model(app_label, model_name)
|
user_model = apps.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
|
||||||
|
|
|
@ -6,7 +6,7 @@ from __future__ import unicode_literals
|
||||||
import getpass
|
import getpass
|
||||||
import unicodedata
|
import unicodedata
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -61,7 +61,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):
|
||||||
if app_cache.get_model('auth', 'Permission') is None:
|
if apps.get_model('auth', 'Permission') is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
if not router.allow_migrate(db, auth_app.Permission):
|
if not router.allow_migrate(db, auth_app.Permission):
|
||||||
|
@ -69,7 +69,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 = app_cache.get_models(app)
|
app_models = apps.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))
|
||||||
|
@ -117,7 +117,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):
|
||||||
if app_cache.get_model('auth', 'Permission') is None:
|
if apps.get_model('auth', 'Permission') is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
UserModel = get_user_model()
|
UserModel = get_user_model()
|
||||||
|
|
|
@ -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 import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -183,21 +183,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, app_cache.get_app_config('auth').models_module)
|
get_validation_errors(new_io, apps.get_app_config('auth').models_module)
|
||||||
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, app_cache.get_app_config('auth').models_module)
|
get_validation_errors(new_io, apps.get_app_config('auth').models_module)
|
||||||
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, app_cache.get_app_config('auth').models_module)
|
get_validation_errors(new_io, apps.get_app_config('auth').models_module)
|
||||||
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())
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
import warnings
|
import warnings
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core import urlresolvers
|
from django.core import urlresolvers
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
|
@ -16,7 +16,7 @@ def get_comment_app():
|
||||||
Get the comment app (i.e. "django.contrib.comments") as defined in the settings
|
Get the comment app (i.e. "django.contrib.comments") as defined in the settings
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
app_config = app_cache.get_app_config(get_comment_app_name().rpartition(".")[2])
|
app_config = apps.get_app_config(get_comment_app_name().rpartition(".")[2])
|
||||||
except LookupError:
|
except LookupError:
|
||||||
raise ImproperlyConfigured("The COMMENTS_APP (%r) "
|
raise ImproperlyConfigured("The COMMENTS_APP (%r) "
|
||||||
"must be in INSTALLED_APPS" % settings.COMMENTS_APP)
|
"must be in INSTALLED_APPS" % settings.COMMENTS_APP)
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
from django import http
|
from django import http
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -49,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 = app_cache.get_model(*ctype.split(".", 1))
|
model = apps.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(
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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 signals
|
from django.db.models import signals
|
||||||
|
@ -12,14 +12,14 @@ def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, *
|
||||||
Creates content types for models in the given app, removing any model
|
Creates content types for models in the given app, removing any model
|
||||||
entries that no longer have a matching model class.
|
entries that no longer have a matching model class.
|
||||||
"""
|
"""
|
||||||
if app_cache.get_model('contenttypes', 'ContentType') is None:
|
if apps.get_model('contenttypes', 'ContentType') is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
if not router.allow_migrate(db, ContentType):
|
if not router.allow_migrate(db, ContentType):
|
||||||
return
|
return
|
||||||
|
|
||||||
ContentType.objects.clear_cache()
|
ContentType.objects.clear_cache()
|
||||||
app_models = app_cache.get_models(app)
|
app_models = apps.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.
|
||||||
|
@ -84,7 +84,7 @@ If you're unsure, answer 'no'.
|
||||||
|
|
||||||
|
|
||||||
def update_all_contenttypes(verbosity=2, **kwargs):
|
def update_all_contenttypes(verbosity=2, **kwargs):
|
||||||
for app_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
update_contenttypes(app_config.models_module, None, verbosity, **kwargs)
|
update_contenttypes(app_config.models_module, None, verbosity, **kwargs)
|
||||||
|
|
||||||
signals.post_migrate.connect(update_contenttypes)
|
signals.post_migrate.connect(update_contenttypes)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -157,8 +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 app_cache.get_model(self.app_label, self.model,
|
return apps.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):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -26,7 +26,7 @@ class KMLSitemap(Sitemap):
|
||||||
"""
|
"""
|
||||||
kml_sources = []
|
kml_sources = []
|
||||||
if sources is None:
|
if sources is None:
|
||||||
sources = app_cache.get_models()
|
sources = apps.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:
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import unicode_literals
|
||||||
|
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -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 = app_cache.get_model(label, model)
|
klass = apps.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))
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from unittest import skipUnless
|
from unittest import skipUnless
|
||||||
|
|
||||||
from django import http
|
from django import http
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import global_settings
|
from django.conf import global_settings
|
||||||
from django.contrib.messages import constants, utils, get_level, set_level
|
from django.contrib.messages import constants, utils, get_level, set_level
|
||||||
from django.contrib.messages.api import MessageFailure
|
from django.contrib.messages.api import MessageFailure
|
||||||
|
@ -15,7 +15,7 @@ from django.utils.translation import ugettext_lazy
|
||||||
|
|
||||||
def skipUnlessAuthIsInstalled(func):
|
def skipUnlessAuthIsInstalled(func):
|
||||||
return skipUnless(
|
return skipUnless(
|
||||||
app_cache.has_app('django.contrib.auth'),
|
apps.has_app('django.contrib.auth'),
|
||||||
"django.contrib.auth isn't installed")(func)
|
"django.contrib.auth isn't installed")(func)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.redirects.models import Redirect
|
from django.contrib.redirects.models import Redirect
|
||||||
from django.contrib.sites.models import get_current_site
|
from django.contrib.sites.models import get_current_site
|
||||||
|
@ -15,7 +15,7 @@ class RedirectFallbackMiddleware(object):
|
||||||
response_redirect_class = http.HttpResponsePermanentRedirect
|
response_redirect_class = http.HttpResponsePermanentRedirect
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
if not app_cache.has_app('django.contrib.sites'):
|
if not apps.has_app('django.contrib.sites'):
|
||||||
raise ImproperlyConfigured(
|
raise ImproperlyConfigured(
|
||||||
"You cannot use RedirectFallbackMiddleware when "
|
"You cannot use RedirectFallbackMiddleware when "
|
||||||
"django.contrib.sites is not installed."
|
"django.contrib.sites is not installed."
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import unicode_literals
|
||||||
|
|
||||||
from unittest import skipUnless
|
from unittest import skipUnless
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
from .base import SitemapTestsBase
|
from .base import SitemapTestsBase
|
||||||
|
@ -10,7 +10,7 @@ from .base import SitemapTestsBase
|
||||||
|
|
||||||
class FlatpagesSitemapTests(SitemapTestsBase):
|
class FlatpagesSitemapTests(SitemapTestsBase):
|
||||||
|
|
||||||
@skipUnless(app_cache.has_app('django.contrib.flatpages'),
|
@skipUnless(apps.has_app('django.contrib.flatpages'),
|
||||||
"django.contrib.flatpages app not installed.")
|
"django.contrib.flatpages app not installed.")
|
||||||
def test_flatpage_sitemap(self):
|
def test_flatpage_sitemap(self):
|
||||||
"Basic FlatPage sitemap test"
|
"Basic FlatPage sitemap test"
|
||||||
|
|
|
@ -4,7 +4,7 @@ import os
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from unittest import skipUnless
|
from unittest import skipUnless
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.sitemaps import Sitemap, GenericSitemap
|
from django.contrib.sitemaps import Sitemap, GenericSitemap
|
||||||
from django.contrib.sites.models import Site
|
from django.contrib.sites.models import Site
|
||||||
|
@ -118,7 +118,7 @@ class HTTPSitemapTests(SitemapTestsBase):
|
||||||
""" % date.today()
|
""" % date.today()
|
||||||
self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
|
self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
|
||||||
|
|
||||||
@skipUnless(app_cache.has_app('django.contrib.sites'),
|
@skipUnless(apps.has_app('django.contrib.sites'),
|
||||||
"django.contrib.sites app not installed.")
|
"django.contrib.sites app not installed.")
|
||||||
def test_sitemap_get_urls_no_site_1(self):
|
def test_sitemap_get_urls_no_site_1(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
from django.core.files.storage import default_storage, Storage, FileSystemStorage
|
from django.core.files.storage import default_storage, Storage, FileSystemStorage
|
||||||
|
@ -43,7 +43,7 @@ class FileSystemFinder(BaseFinder):
|
||||||
A static files finder that uses the ``STATICFILES_DIRS`` setting
|
A static files finder that uses the ``STATICFILES_DIRS`` setting
|
||||||
to locate files.
|
to locate files.
|
||||||
"""
|
"""
|
||||||
def __init__(self, apps=None, *args, **kwargs):
|
def __init__(self, app_names=None, *args, **kwargs):
|
||||||
# List of locations with static files
|
# List of locations with static files
|
||||||
self.locations = []
|
self.locations = []
|
||||||
# Maps dir paths to an appropriate storage instance
|
# Maps dir paths to an appropriate storage instance
|
||||||
|
@ -114,15 +114,15 @@ class AppDirectoriesFinder(BaseFinder):
|
||||||
"""
|
"""
|
||||||
storage_class = AppStaticStorage
|
storage_class = AppStaticStorage
|
||||||
|
|
||||||
def __init__(self, apps=None, *args, **kwargs):
|
def __init__(self, app_names=None, *args, **kwargs):
|
||||||
# The list of apps that are handled
|
# The list of apps that are handled
|
||||||
self.apps = []
|
self.apps = []
|
||||||
# Mapping of app names to storage instances
|
# Mapping of app names to storage instances
|
||||||
self.storages = OrderedDict()
|
self.storages = OrderedDict()
|
||||||
if apps is None:
|
if app_names is None:
|
||||||
app_configs = app_cache.get_app_configs()
|
app_configs = apps.get_app_configs()
|
||||||
apps = [app_config.name for app_config in app_configs]
|
app_names = [app_config.name for app_config in app_configs]
|
||||||
for app in apps:
|
for app in app_names:
|
||||||
app_storage = self.storage_class(app)
|
app_storage = self.storage_class(app)
|
||||||
if os.path.isdir(app_storage.location):
|
if os.path.isdir(app_storage.location):
|
||||||
self.storages[app] = app_storage
|
self.storages[app] = app_storage
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
|
|
||||||
|
@ -32,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 app_cache.get_models():
|
for cls in apps.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():
|
||||||
|
|
|
@ -112,17 +112,17 @@ def get_commands():
|
||||||
except ImproperlyConfigured:
|
except ImproperlyConfigured:
|
||||||
# Still useful for commands that do not require functional
|
# Still useful for commands that do not require functional
|
||||||
# settings, like startproject or help.
|
# settings, like startproject or help.
|
||||||
apps = []
|
app_names = []
|
||||||
else:
|
else:
|
||||||
# Populate the app cache outside of the try/except block to avoid
|
# Populate the app registry outside of the try/except block to
|
||||||
# catching ImproperlyConfigured errors that aren't caused by the
|
# avoid catching ImproperlyConfigured errors that aren't caused
|
||||||
# absence of a settings module.
|
# by the absence of a settings module.
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
app_configs = app_cache.get_app_configs()
|
app_configs = apps.get_app_configs()
|
||||||
apps = [app_config.name for app_config in app_configs]
|
app_names = [app_config.name for app_config in app_configs]
|
||||||
|
|
||||||
# Find and load the management module for each installed app.
|
# Find and load the management module for each installed app.
|
||||||
for app_name in apps:
|
for app_name in app_names:
|
||||||
try:
|
try:
|
||||||
path = find_management_module(app_name)
|
path = find_management_module(app_name)
|
||||||
_commands.update(dict((name, app_name) for name in find_commands(path)))
|
_commands.update(dict((name, app_name) for name in find_commands(path)))
|
||||||
|
@ -346,8 +346,8 @@ class ManagementUtility(object):
|
||||||
elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear',
|
elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear',
|
||||||
'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'):
|
'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'):
|
||||||
try:
|
try:
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
app_configs = app_cache.get_app_configs()
|
app_configs = apps.get_app_configs()
|
||||||
# Get the last part of the dotted path as the app name.
|
# Get the last part of the dotted path as the app name.
|
||||||
options += [(app_config.label, 0) for app_config in app_configs]
|
options += [(app_config.label, 0) for app_config in app_configs]
|
||||||
except ImportError:
|
except ImportError:
|
||||||
|
|
|
@ -341,16 +341,16 @@ class AppCommand(BaseCommand):
|
||||||
args = '<appname appname ...>'
|
args = '<appname appname ...>'
|
||||||
|
|
||||||
def handle(self, *app_labels, **options):
|
def handle(self, *app_labels, **options):
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
if not app_labels:
|
if not app_labels:
|
||||||
raise CommandError('Enter at least one appname.')
|
raise CommandError('Enter at least one appname.')
|
||||||
# Populate models and don't use only_with_models_module=True when
|
# Populate models and don't use only_with_models_module=True when
|
||||||
# calling get_app_config() to tell apart missing apps from apps
|
# calling get_app_config() to tell apart missing apps from apps
|
||||||
# without a model module -- which can't be supported with the legacy
|
# without a model module -- which can't be supported with the legacy
|
||||||
# API since it passes the models module to handle_app().
|
# API since it passes the models module to handle_app().
|
||||||
app_cache.populate_models()
|
apps.populate_models()
|
||||||
try:
|
try:
|
||||||
app_configs = [app_cache.get_app_config(app_label) for app_label in app_labels]
|
app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
|
||||||
except (LookupError, ImportError) as e:
|
except (LookupError, 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 = []
|
||||||
|
|
|
@ -37,7 +37,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.apps import app_cache
|
from django.apps import apps
|
||||||
|
|
||||||
format = options.get('format')
|
format = options.get('format')
|
||||||
indent = options.get('indent')
|
indent = options.get('indent')
|
||||||
|
@ -63,13 +63,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 = app_cache.get_model(app_label, model_name)
|
model_obj = apps.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 = app_cache.get_app_config(exclude).models_module
|
app_obj = apps.get_app_config(exclude).models_module
|
||||||
if app_obj is not None:
|
if app_obj is not None:
|
||||||
excluded_apps.add(app_obj)
|
excluded_apps.add(app_obj)
|
||||||
except LookupError:
|
except LookupError:
|
||||||
|
@ -79,7 +79,7 @@ class Command(BaseCommand):
|
||||||
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_config.models_module, None)
|
app_list = OrderedDict((app_config.models_module, None)
|
||||||
for app_config in app_cache.get_app_configs(only_with_models_module=True)
|
for app_config in apps.get_app_configs(only_with_models_module=True)
|
||||||
if app_config.models_module not in excluded_apps)
|
if app_config.models_module not in excluded_apps)
|
||||||
else:
|
else:
|
||||||
if len(app_labels) > 1 and primary_keys:
|
if len(app_labels) > 1 and primary_keys:
|
||||||
|
@ -89,12 +89,12 @@ class Command(BaseCommand):
|
||||||
try:
|
try:
|
||||||
app_label, model_label = label.split('.')
|
app_label, model_label = label.split('.')
|
||||||
try:
|
try:
|
||||||
app = app_cache.get_app_config(app_label).models_module
|
app = apps.get_app_config(app_label).models_module
|
||||||
except LookupError:
|
except LookupError:
|
||||||
raise CommandError("Unknown application: %s" % app_label)
|
raise CommandError("Unknown application: %s" % app_label)
|
||||||
if app is None or app in excluded_apps:
|
if app is None or app in excluded_apps:
|
||||||
continue
|
continue
|
||||||
model = app_cache.get_model(app_label, model_label)
|
model = apps.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))
|
||||||
|
|
||||||
|
@ -109,7 +109,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 = app_cache.get_app_config(app_label).models_module
|
app = apps.get_app_config(app_label).models_module
|
||||||
except LookupError:
|
except LookupError:
|
||||||
raise CommandError("Unknown application: %s" % app_label)
|
raise CommandError("Unknown application: %s" % app_label)
|
||||||
if app is None or app in excluded_apps:
|
if app is None or app in excluded_apps:
|
||||||
|
@ -162,13 +162,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.apps import app_cache
|
from django.apps import apps
|
||||||
# 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 = app_cache.get_models(app)
|
model_list = apps.get_models(app)
|
||||||
|
|
||||||
for model in model_list:
|
for model in model_list:
|
||||||
models.add(model)
|
models.add(model)
|
||||||
|
@ -176,7 +176,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 = [app_cache.get_model(*d.split('.')) for d in deps]
|
deps = [apps.get_model(*d.split('.')) for d in deps]
|
||||||
else:
|
else:
|
||||||
deps = []
|
deps = []
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,7 @@ 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.apps import apps
|
||||||
from django.db import connections, router, transaction, 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
|
||||||
|
@ -41,7 +41,7 @@ class Command(NoArgsCommand):
|
||||||
|
|
||||||
# Import the 'management' module within each installed app, to register
|
# Import the 'management' module within each installed app, to register
|
||||||
# dispatcher events.
|
# dispatcher events.
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
try:
|
try:
|
||||||
import_module('.management', app_config.name)
|
import_module('.management', app_config.name)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
|
@ -93,6 +93,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_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
all_models.extend(router.get_migratable_models(app_config.models_module, database, include_auto_created=True))
|
all_models.extend(router.get_migratable_models(app_config.models_module, 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)
|
||||||
|
|
|
@ -7,7 +7,7 @@ import warnings
|
||||||
import zipfile
|
import zipfile
|
||||||
from optparse import make_option
|
from optparse import make_option
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -230,7 +230,7 @@ class Command(BaseCommand):
|
||||||
current directory.
|
current directory.
|
||||||
"""
|
"""
|
||||||
dirs = []
|
dirs = []
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
d = os.path.join(app_config.path, 'fixtures')
|
d = os.path.join(app_config.path, 'fixtures')
|
||||||
if os.path.isdir(d):
|
if os.path.isdir(d):
|
||||||
dirs.append(d)
|
dirs.append(d)
|
||||||
|
|
|
@ -3,7 +3,7 @@ import os
|
||||||
import operator
|
import operator
|
||||||
from optparse import make_option
|
from optparse import make_option
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.core.management.base import BaseCommand, CommandError
|
from django.core.management.base import BaseCommand, CommandError
|
||||||
from django.db import connections, DEFAULT_DB_ALIAS, migrations
|
from django.db import connections, DEFAULT_DB_ALIAS, migrations
|
||||||
from django.db.migrations.loader import MigrationLoader
|
from django.db.migrations.loader import MigrationLoader
|
||||||
|
@ -37,7 +37,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:
|
||||||
app_cache.get_app_config(app_label)
|
apps.get_app_config(app_label)
|
||||||
except LookupError:
|
except LookupError:
|
||||||
bad_app_labels.add(app_label)
|
bad_app_labels.add(app_label)
|
||||||
if bad_app_labels:
|
if bad_app_labels:
|
||||||
|
@ -72,7 +72,7 @@ class Command(BaseCommand):
|
||||||
# Detect changes
|
# Detect changes
|
||||||
autodetector = MigrationAutodetector(
|
autodetector = MigrationAutodetector(
|
||||||
loader.graph.project_state(),
|
loader.graph.project_state(),
|
||||||
ProjectState.from_app_cache(app_cache),
|
ProjectState.from_apps(apps),
|
||||||
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)
|
||||||
|
|
|
@ -6,7 +6,7 @@ from importlib import import_module
|
||||||
import itertools
|
import itertools
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -46,7 +46,7 @@ class Command(BaseCommand):
|
||||||
|
|
||||||
# Import the 'management' module within each installed app, to register
|
# Import the 'management' module within each installed app, to register
|
||||||
# dispatcher events.
|
# dispatcher events.
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
if module_has_submodule(app_config.app_module, "management"):
|
if module_has_submodule(app_config.app_module, "management"):
|
||||||
import_module('.management', app_config.name)
|
import_module('.management', app_config.name)
|
||||||
|
|
||||||
|
@ -135,7 +135,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(app_cache),
|
ProjectState.from_apps(apps),
|
||||||
)
|
)
|
||||||
changes = autodetector.changes(graph=executor.loader.graph)
|
changes = autodetector.changes(graph=executor.loader.graph)
|
||||||
if changes:
|
if changes:
|
||||||
|
@ -167,8 +167,8 @@ class Command(BaseCommand):
|
||||||
else:
|
else:
|
||||||
self.stdout.write(self.style.MIGRATE_SUCCESS(" OK"))
|
self.stdout.write(self.style.MIGRATE_SUCCESS(" OK"))
|
||||||
|
|
||||||
def sync_apps(self, connection, apps):
|
def sync_apps(self, connection, app_labels):
|
||||||
"Runs the old syncdb-style operation on a list of apps."
|
"Runs the old syncdb-style operation on a list of app_labels."
|
||||||
cursor = connection.cursor()
|
cursor = connection.cursor()
|
||||||
|
|
||||||
# Get a list of already installed *models* so that references work right.
|
# Get a list of already installed *models* so that references work right.
|
||||||
|
@ -181,8 +181,8 @@ class Command(BaseCommand):
|
||||||
all_models = [
|
all_models = [
|
||||||
(app_config.label,
|
(app_config.label,
|
||||||
router.get_migratable_models(app_config.models_module, connection.alias, include_auto_created=True))
|
router.get_migratable_models(app_config.models_module, connection.alias, include_auto_created=True))
|
||||||
for app_config in app_cache.get_app_configs(only_with_models_module=True)
|
for app_config in apps.get_app_configs(only_with_models_module=True)
|
||||||
if app_config.label in apps
|
if app_config.label in app_labels
|
||||||
]
|
]
|
||||||
|
|
||||||
def model_installed(model):
|
def model_installed(model):
|
||||||
|
@ -277,7 +277,7 @@ class Command(BaseCommand):
|
||||||
|
|
||||||
return created_models
|
return created_models
|
||||||
|
|
||||||
def show_migration_list(self, connection, apps=None):
|
def show_migration_list(self, connection, app_names=None):
|
||||||
"""
|
"""
|
||||||
Shows a list of all migrations on the system, or only those of
|
Shows a list of all migrations on the system, or only those of
|
||||||
some named apps.
|
some named apps.
|
||||||
|
@ -286,24 +286,24 @@ class Command(BaseCommand):
|
||||||
loader = MigrationLoader(connection)
|
loader = MigrationLoader(connection)
|
||||||
graph = loader.graph
|
graph = loader.graph
|
||||||
# If we were passed a list of apps, validate it
|
# If we were passed a list of apps, validate it
|
||||||
if apps:
|
if app_names:
|
||||||
invalid_apps = []
|
invalid_apps = []
|
||||||
for app in apps:
|
for app_name in app_names:
|
||||||
if app not in loader.migrated_apps:
|
if app_name not in loader.migrated_apps:
|
||||||
invalid_apps.append(app)
|
invalid_apps.append(app_name)
|
||||||
if invalid_apps:
|
if invalid_apps:
|
||||||
raise CommandError("No migrations present for: %s" % (", ".join(invalid_apps)))
|
raise CommandError("No migrations present for: %s" % (", ".join(invalid_apps)))
|
||||||
# Otherwise, show all apps in alphabetic order
|
# Otherwise, show all apps in alphabetic order
|
||||||
else:
|
else:
|
||||||
apps = sorted(loader.migrated_apps)
|
app_names = sorted(loader.migrated_apps)
|
||||||
# For each app, print its migrations in order from oldest (roots) to
|
# For each app, print its migrations in order from oldest (roots) to
|
||||||
# newest (leaves).
|
# newest (leaves).
|
||||||
for app in apps:
|
for app_name in app_names:
|
||||||
self.stdout.write(app, self.style.MIGRATE_LABEL)
|
self.stdout.write(app_name, self.style.MIGRATE_LABEL)
|
||||||
shown = set()
|
shown = set()
|
||||||
for node in graph.leaf_nodes(app):
|
for node in graph.leaf_nodes(app_name):
|
||||||
for plan_node in graph.forwards_plan(node):
|
for plan_node in graph.forwards_plan(node):
|
||||||
if plan_node not in shown and plan_node[0] == app:
|
if plan_node not in shown and plan_node[0] == app_name:
|
||||||
# Give it a nice title if it's a squashed one
|
# Give it a nice title if it's a squashed one
|
||||||
title = plan_node[1]
|
title = plan_node[1]
|
||||||
if graph.nodes[plan_node].replaces:
|
if graph.nodes[plan_node].replaces:
|
||||||
|
|
|
@ -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 import app_cache
|
from django.apps import apps
|
||||||
app_cache.get_models()
|
apps.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)
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import unicode_literals
|
||||||
|
|
||||||
from optparse import make_option
|
from optparse import make_option
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.core.management.base import AppCommand
|
from django.core.management.base import AppCommand
|
||||||
from django.db import connections, DEFAULT_DB_ALIAS
|
from django.db import connections, DEFAULT_DB_ALIAS
|
||||||
|
|
||||||
|
@ -21,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, app_cache.get_models(app, include_auto_created=True)))
|
return '\n'.join(connection.ops.sequence_reset_sql(self.style, apps.get_models(app, include_auto_created=True)))
|
||||||
|
|
|
@ -5,7 +5,7 @@ import os
|
||||||
import re
|
import re
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -25,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 = app_cache.get_models(app, include_auto_created=True)
|
app_models = apps.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)
|
||||||
|
@ -169,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 = app_cache.get_app_config(model._meta.app_label).path
|
app_dir = apps.get_app_config(model._meta.app_label).path
|
||||||
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
|
||||||
|
@ -207,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_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
if verbosity >= 2:
|
if verbosity >= 2:
|
||||||
print("Running pre-migrate handlers for application %s" % app_config.label)
|
print("Running pre-migrate handlers for application %s" % app_config.label)
|
||||||
models.signals.pre_migrate.send(
|
models.signals.pre_migrate.send(
|
||||||
|
@ -221,7 +221,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_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
if verbosity >= 2:
|
if verbosity >= 2:
|
||||||
print("Running post-migrate handlers for application %s" % app_config.label)
|
print("Running post-migrate handlers for application %s" % app_config.label)
|
||||||
models.signals.post_migrate.send(
|
models.signals.post_migrate.send(
|
||||||
|
|
|
@ -26,13 +26,13 @@ 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 import app_cache
|
from django.apps import apps
|
||||||
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 cls in app_cache.get_models(app, include_swapped=True):
|
for cls in apps.get_models(app, include_swapped=True):
|
||||||
opts = cls._meta
|
opts = cls._meta
|
||||||
|
|
||||||
# Check swappable attribute.
|
# Check swappable attribute.
|
||||||
|
@ -42,7 +42,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 app_cache.get_model(app_label, model_name):
|
if not apps.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
|
||||||
|
@ -152,7 +152,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 app_cache.get_models():
|
if f.rel.to not in apps.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:
|
||||||
|
@ -207,7 +207,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 app_cache.get_models():
|
if f.rel.to not in apps.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:
|
||||||
|
@ -265,7 +265,7 @@ def get_validation_errors(outfile, app=None):
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
seen_to = True
|
seen_to = True
|
||||||
if f.rel.through not in app_cache.get_models(include_auto_created=True):
|
if f.rel.through not in apps.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)
|
||||||
|
|
|
@ -3,7 +3,7 @@ Module for abstract serializer/unserializer base classes.
|
||||||
"""
|
"""
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
|
|
||||||
|
@ -137,9 +137,9 @@ class Deserializer(six.Iterator):
|
||||||
self.stream = six.StringIO(stream_or_string)
|
self.stream = six.StringIO(stream_or_string)
|
||||||
else:
|
else:
|
||||||
self.stream = stream_or_string
|
self.stream = stream_or_string
|
||||||
# Make sure the app cache is loaded before deserialization starts
|
# Make sure the app registy is loaded before deserialization starts
|
||||||
# (otherwise subclass calls to get_model() and friends might fail...)
|
# (otherwise subclass calls to get_model() and friends might fail...)
|
||||||
app_cache.populate_models()
|
apps.populate_models()
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return self
|
return self
|
||||||
|
|
|
@ -5,7 +5,7 @@ other serializers.
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -88,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)
|
||||||
|
|
||||||
app_cache.populate_models()
|
apps.populate_models()
|
||||||
|
|
||||||
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.
|
||||||
|
@ -155,7 +155,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 = app_cache.get_model(*model_identifier.split("."))
|
Model = apps.get_model(*model_identifier.split("."))
|
||||||
except TypeError:
|
except TypeError:
|
||||||
Model = None
|
Model = None
|
||||||
if Model is None:
|
if Model is None:
|
||||||
|
|
|
@ -4,7 +4,7 @@ XML serializer.
|
||||||
|
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -277,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 = app_cache.get_model(*model_identifier.split("."))
|
Model = apps.get_model(*model_identifier.split("."))
|
||||||
except TypeError:
|
except TypeError:
|
||||||
Model = None
|
Model = None
|
||||||
if Model is None:
|
if Model is None:
|
||||||
|
|
|
@ -1268,10 +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.apps import app_cache
|
from django.apps import apps
|
||||||
from django.db import router
|
from django.db import router
|
||||||
tables = set()
|
tables = set()
|
||||||
for app_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
for model in router.get_migratable_models(app_config.models_module, self.connection.alias):
|
for model in router.get_migratable_models(app_config.models_module, self.connection.alias):
|
||||||
if not model._meta.managed:
|
if not model._meta.managed:
|
||||||
continue
|
continue
|
||||||
|
@ -1289,10 +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.apps import app_cache
|
from django.apps import apps
|
||||||
from django.db import router
|
from django.db import router
|
||||||
all_models = []
|
all_models = []
|
||||||
for app_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
all_models.extend(router.get_migratable_models(app_config.models_module, self.connection.alias))
|
all_models.extend(router.get_migratable_models(app_config.models_module, self.connection.alias))
|
||||||
tables = list(map(self.table_name_converter, tables))
|
tables = list(map(self.table_name_converter, tables))
|
||||||
return set([
|
return set([
|
||||||
|
@ -1302,12 +1302,12 @@ 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.apps import apps
|
||||||
from django.db import models, router
|
from django.db import models, router
|
||||||
|
|
||||||
sequence_list = []
|
sequence_list = []
|
||||||
|
|
||||||
for app_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
for model in router.get_migratable_models(app_config.models_module, self.connection.alias):
|
for model in router.get_migratable_models(app_config.models_module, self.connection.alias):
|
||||||
if not model._meta.managed:
|
if not model._meta.managed:
|
||||||
continue
|
continue
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db.backends.schema import BaseDatabaseSchemaEditor
|
from django.db.backends.schema import BaseDatabaseSchemaEditor
|
||||||
from django.db.models.fields.related import ManyToManyField
|
from django.db.models.fields.related import ManyToManyField
|
||||||
|
|
||||||
|
@ -38,14 +38,14 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
|
||||||
for field in delete_fields:
|
for field in delete_fields:
|
||||||
del body[field.name]
|
del body[field.name]
|
||||||
del mapping[field.column]
|
del mapping[field.column]
|
||||||
# Work inside a new AppCache
|
# Work inside a new app registry
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
# Construct a new model for the new state
|
# Construct a new model for the new state
|
||||||
meta_contents = {
|
meta_contents = {
|
||||||
'app_label': model._meta.app_label,
|
'app_label': model._meta.app_label,
|
||||||
'db_table': model._meta.db_table + "__new",
|
'db_table': model._meta.db_table + "__new",
|
||||||
'unique_together': model._meta.unique_together if override_uniques is None else override_uniques,
|
'unique_together': model._meta.unique_together if override_uniques is None else override_uniques,
|
||||||
'app_cache': app_cache,
|
'apps': apps,
|
||||||
}
|
}
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
meta = type("Meta", tuple(), meta_contents)
|
||||||
body['Meta'] = meta
|
body['Meta'] = meta
|
||||||
|
|
|
@ -47,19 +47,19 @@ class MigrationAutodetector(object):
|
||||||
"""
|
"""
|
||||||
# We'll store migrations as lists by app names for now
|
# We'll store migrations as lists by app names for now
|
||||||
self.migrations = {}
|
self.migrations = {}
|
||||||
old_app_cache = self.from_state.render()
|
old_apps = self.from_state.render()
|
||||||
new_app_cache = self.to_state.render()
|
new_apps = self.to_state.render()
|
||||||
# Prepare lists of old/new model keys that we care about
|
# Prepare lists of old/new model keys that we care about
|
||||||
# (i.e. ignoring proxy ones)
|
# (i.e. ignoring proxy ones)
|
||||||
old_model_keys = [
|
old_model_keys = [
|
||||||
(al, mn)
|
(al, mn)
|
||||||
for al, mn in self.from_state.models.keys()
|
for al, mn in self.from_state.models.keys()
|
||||||
if not old_app_cache.get_model(al, mn)._meta.proxy
|
if not old_apps.get_model(al, mn)._meta.proxy
|
||||||
]
|
]
|
||||||
new_model_keys = [
|
new_model_keys = [
|
||||||
(al, mn)
|
(al, mn)
|
||||||
for al, mn in self.to_state.models.keys()
|
for al, mn in self.to_state.models.keys()
|
||||||
if not new_app_cache.get_model(al, mn)._meta.proxy
|
if not new_apps.get_model(al, mn)._meta.proxy
|
||||||
]
|
]
|
||||||
# Adding models. Phase 1 is adding models with no outward relationships.
|
# Adding models. Phase 1 is adding models with no outward relationships.
|
||||||
added_models = set(new_model_keys) - set(old_model_keys)
|
added_models = set(new_model_keys) - set(old_model_keys)
|
||||||
|
@ -68,7 +68,7 @@ class MigrationAutodetector(object):
|
||||||
model_state = self.to_state.models[app_label, model_name]
|
model_state = self.to_state.models[app_label, model_name]
|
||||||
# Are there any relationships out from this model? if so, punt it to the next phase.
|
# Are there any relationships out from this model? if so, punt it to the next phase.
|
||||||
related_fields = []
|
related_fields = []
|
||||||
for field in new_app_cache.get_model(app_label, model_name)._meta.local_fields:
|
for field in new_apps.get_model(app_label, model_name)._meta.local_fields:
|
||||||
if field.rel:
|
if field.rel:
|
||||||
if field.rel.to:
|
if field.rel.to:
|
||||||
related_fields.append((field.name, field.rel.to._meta.app_label.lower(), field.rel.to._meta.object_name.lower()))
|
related_fields.append((field.name, field.rel.to._meta.app_label.lower(), field.rel.to._meta.object_name.lower()))
|
||||||
|
|
|
@ -129,10 +129,10 @@ class MigrationExecutor(object):
|
||||||
on initial migrations (as it only looks for CreateModel).
|
on initial migrations (as it only looks for CreateModel).
|
||||||
"""
|
"""
|
||||||
project_state = self.loader.graph.project_state((migration.app_label, migration.name), at_end=True)
|
project_state = self.loader.graph.project_state((migration.app_label, migration.name), at_end=True)
|
||||||
app_cache = project_state.render()
|
apps = project_state.render()
|
||||||
for operation in migration.operations:
|
for operation in migration.operations:
|
||||||
if isinstance(operation, migrations.CreateModel):
|
if isinstance(operation, migrations.CreateModel):
|
||||||
model = app_cache.get_model(migration.app_label, operation.name)
|
model = apps.get_model(migration.app_label, operation.name)
|
||||||
if model._meta.db_table not in self.connection.introspection.get_table_list(self.connection.cursor()):
|
if model._meta.db_table not in self.connection.introspection.get_table_list(self.connection.cursor()):
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
|
@ -2,7 +2,7 @@ from importlib import import_module
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -46,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' % app_cache.get_app_config(app_label).name
|
return '%s.migrations' % apps.get_app_config(app_label).name
|
||||||
|
|
||||||
def load_disk(self):
|
def load_disk(self):
|
||||||
"""
|
"""
|
||||||
|
@ -55,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_config in app_cache.get_app_configs(only_with_models_module=True):
|
for app_config in apps.get_app_configs(only_with_models_module=True):
|
||||||
# Get the migrations module directory
|
# Get the migrations module directory
|
||||||
module_name = self.migrations_module(app_config.label)
|
module_name = self.migrations_module(app_config.label)
|
||||||
was_loaded = module_name in sys.modules
|
was_loaded = module_name in sys.modules
|
||||||
|
|
|
@ -20,14 +20,14 @@ class CreateModel(Operation):
|
||||||
state.models[app_label, self.name.lower()] = ModelState(app_label, self.name, self.fields, self.options, self.bases)
|
state.models[app_label, self.name.lower()] = ModelState(app_label, self.name, self.fields, self.options, self.bases)
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
app_cache = to_state.render()
|
apps = to_state.render()
|
||||||
model = app_cache.get_model(app_label, self.name)
|
model = apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, model):
|
if router.allow_migrate(schema_editor.connection.alias, model):
|
||||||
schema_editor.create_model(model)
|
schema_editor.create_model(model)
|
||||||
|
|
||||||
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
app_cache = from_state.render()
|
apps = from_state.render()
|
||||||
model = app_cache.get_model(app_label, self.name)
|
model = apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, model):
|
if router.allow_migrate(schema_editor.connection.alias, model):
|
||||||
schema_editor.delete_model(model)
|
schema_editor.delete_model(model)
|
||||||
|
|
||||||
|
@ -73,14 +73,14 @@ class DeleteModel(Operation):
|
||||||
del state.models[app_label, self.name.lower()]
|
del state.models[app_label, self.name.lower()]
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
app_cache = from_state.render()
|
apps = from_state.render()
|
||||||
model = app_cache.get_model(app_label, self.name)
|
model = apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, model):
|
if router.allow_migrate(schema_editor.connection.alias, model):
|
||||||
schema_editor.delete_model(model)
|
schema_editor.delete_model(model)
|
||||||
|
|
||||||
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
app_cache = to_state.render()
|
apps = to_state.render()
|
||||||
model = app_cache.get_model(app_label, self.name)
|
model = apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, model):
|
if router.allow_migrate(schema_editor.connection.alias, model):
|
||||||
schema_editor.create_model(model)
|
schema_editor.create_model(model)
|
||||||
|
|
||||||
|
@ -106,10 +106,10 @@ class RenameModel(Operation):
|
||||||
del state.models[app_label, self.old_name.lower()]
|
del state.models[app_label, self.old_name.lower()]
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
old_app_cache = from_state.render()
|
old_apps = from_state.render()
|
||||||
new_app_cache = to_state.render()
|
new_apps = to_state.render()
|
||||||
old_model = old_app_cache.get_model(app_label, self.old_name)
|
old_model = old_apps.get_model(app_label, self.old_name)
|
||||||
new_model = new_app_cache.get_model(app_label, self.new_name)
|
new_model = new_apps.get_model(app_label, self.new_name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
||||||
schema_editor.alter_db_table(
|
schema_editor.alter_db_table(
|
||||||
new_model,
|
new_model,
|
||||||
|
@ -118,10 +118,10 @@ class RenameModel(Operation):
|
||||||
)
|
)
|
||||||
|
|
||||||
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
def database_backwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
old_app_cache = from_state.render()
|
old_apps = from_state.render()
|
||||||
new_app_cache = to_state.render()
|
new_apps = to_state.render()
|
||||||
old_model = old_app_cache.get_model(app_label, self.new_name)
|
old_model = old_apps.get_model(app_label, self.new_name)
|
||||||
new_model = new_app_cache.get_model(app_label, self.old_name)
|
new_model = new_apps.get_model(app_label, self.old_name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
||||||
schema_editor.alter_db_table(
|
schema_editor.alter_db_table(
|
||||||
new_model,
|
new_model,
|
||||||
|
@ -152,10 +152,10 @@ class AlterModelTable(Operation):
|
||||||
state.models[app_label, self.name.lower()].options["db_table"] = self.table
|
state.models[app_label, self.name.lower()].options["db_table"] = self.table
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
old_app_cache = from_state.render()
|
old_apps = from_state.render()
|
||||||
new_app_cache = to_state.render()
|
new_apps = to_state.render()
|
||||||
old_model = old_app_cache.get_model(app_label, self.name)
|
old_model = old_apps.get_model(app_label, self.name)
|
||||||
new_model = new_app_cache.get_model(app_label, self.name)
|
new_model = new_apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
||||||
schema_editor.alter_db_table(
|
schema_editor.alter_db_table(
|
||||||
new_model,
|
new_model,
|
||||||
|
@ -189,10 +189,10 @@ class AlterUniqueTogether(Operation):
|
||||||
model_state.options["unique_together"] = self.unique_together
|
model_state.options["unique_together"] = self.unique_together
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
old_app_cache = from_state.render()
|
old_apps = from_state.render()
|
||||||
new_app_cache = to_state.render()
|
new_apps = to_state.render()
|
||||||
old_model = old_app_cache.get_model(app_label, self.name)
|
old_model = old_apps.get_model(app_label, self.name)
|
||||||
new_model = new_app_cache.get_model(app_label, self.name)
|
new_model = new_apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
||||||
schema_editor.alter_unique_together(
|
schema_editor.alter_unique_together(
|
||||||
new_model,
|
new_model,
|
||||||
|
@ -225,10 +225,10 @@ class AlterIndexTogether(Operation):
|
||||||
model_state.options["index_together"] = self.index_together
|
model_state.options["index_together"] = self.index_together
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
old_app_cache = from_state.render()
|
old_apps = from_state.render()
|
||||||
new_app_cache = to_state.render()
|
new_apps = to_state.render()
|
||||||
old_model = old_app_cache.get_model(app_label, self.name)
|
old_model = old_apps.get_model(app_label, self.name)
|
||||||
new_model = new_app_cache.get_model(app_label, self.name)
|
new_model = new_apps.get_model(app_label, self.name)
|
||||||
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
if router.allow_migrate(schema_editor.connection.alias, new_model):
|
||||||
schema_editor.alter_index_together(
|
schema_editor.alter_index_together(
|
||||||
new_model,
|
new_model,
|
||||||
|
|
|
@ -134,7 +134,7 @@ class RunPython(Operation):
|
||||||
|
|
||||||
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
def database_forwards(self, app_label, schema_editor, from_state, to_state):
|
||||||
# We now execute the Python code in a context that contains a 'models'
|
# We now execute the Python code in a context that contains a 'models'
|
||||||
# object, representing the versioned models as an AppCache.
|
# object, representing the versioned models as an app registry.
|
||||||
# We could try to override the global cache, but then people will still
|
# We could try to override the global cache, but then people will still
|
||||||
# use direct imports, so we go with a documentation approach instead.
|
# use direct imports, so we go with a documentation approach instead.
|
||||||
if callable(self.code):
|
if callable(self.code):
|
||||||
|
|
|
@ -2,7 +2,7 @@ import importlib
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
|
||||||
|
@ -28,7 +28,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:
|
||||||
app_config = app_cache.get_app_config(app_label)
|
app_config = apps.get_app_config(app_label)
|
||||||
except LookupError: # It's a fake app.
|
except LookupError: # It's a fake app.
|
||||||
return self.defaults.get("ask_initial", False)
|
return self.defaults.get("ask_initial", False)
|
||||||
migrations_import_path = "%s.migrations" % app_config.name
|
migrations_import_path = "%s.migrations" % app_config.name
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
|
|
||||||
|
@ -22,7 +22,7 @@ class MigrationRecorder(object):
|
||||||
applied = models.DateTimeField(default=now)
|
applied = models.DateTimeField(default=now)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
db_table = "django_migrations"
|
db_table = "django_migrations"
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.db.models.options import DEFAULT_NAMES, normalize_unique_together
|
from django.db.models.options import DEFAULT_NAMES, normalize_unique_together
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
|
@ -18,7 +18,7 @@ class ProjectState(object):
|
||||||
|
|
||||||
def __init__(self, models=None):
|
def __init__(self, models=None):
|
||||||
self.models = models or {}
|
self.models = models or {}
|
||||||
self.app_cache = None
|
self.apps = None
|
||||||
|
|
||||||
def add_model_state(self, model_state):
|
def add_model_state(self, model_state):
|
||||||
self.models[(model_state.app_label, model_state.name.lower())] = model_state
|
self.models[(model_state.app_label, model_state.name.lower())] = model_state
|
||||||
|
@ -30,9 +30,9 @@ class ProjectState(object):
|
||||||
)
|
)
|
||||||
|
|
||||||
def render(self):
|
def render(self):
|
||||||
"Turns the project state into actual models in a new AppCache"
|
"Turns the project state into actual models in a new Apps"
|
||||||
if self.app_cache is None:
|
if self.apps is None:
|
||||||
self.app_cache = AppCache()
|
self.apps = Apps()
|
||||||
# We keep trying to render the models in a loop, ignoring invalid
|
# We keep trying to render the models in a loop, ignoring invalid
|
||||||
# base errors, until the size of the unrendered models doesn't
|
# base errors, until the size of the unrendered models doesn't
|
||||||
# decrease by at least one, meaning there's a base dependency loop/
|
# decrease by at least one, meaning there's a base dependency loop/
|
||||||
|
@ -42,19 +42,19 @@ class ProjectState(object):
|
||||||
new_unrendered_models = []
|
new_unrendered_models = []
|
||||||
for model in unrendered_models:
|
for model in unrendered_models:
|
||||||
try:
|
try:
|
||||||
model.render(self.app_cache)
|
model.render(self.apps)
|
||||||
except InvalidBasesError:
|
except InvalidBasesError:
|
||||||
new_unrendered_models.append(model)
|
new_unrendered_models.append(model)
|
||||||
if len(new_unrendered_models) == len(unrendered_models):
|
if len(new_unrendered_models) == len(unrendered_models):
|
||||||
raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
|
raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models)
|
||||||
unrendered_models = new_unrendered_models
|
unrendered_models = new_unrendered_models
|
||||||
return self.app_cache
|
return self.apps
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_app_cache(cls, app_cache):
|
def from_apps(cls, apps):
|
||||||
"Takes in an AppCache and returns a ProjectState matching it"
|
"Takes in an Apps and returns a ProjectState matching it"
|
||||||
app_models = {}
|
app_models = {}
|
||||||
for model in app_cache.get_models():
|
for model in apps.get_models():
|
||||||
model_state = ModelState.from_model(model)
|
model_state = ModelState.from_model(model)
|
||||||
app_models[(model_state.app_label, model_state.name.lower())] = model_state
|
app_models[(model_state.app_label, model_state.name.lower())] = model_state
|
||||||
return cls(app_models)
|
return cls(app_models)
|
||||||
|
@ -123,7 +123,7 @@ class ModelState(object):
|
||||||
options = {}
|
options = {}
|
||||||
for name in DEFAULT_NAMES:
|
for name in DEFAULT_NAMES:
|
||||||
# Ignore some special options
|
# Ignore some special options
|
||||||
if name in ["app_cache", "app_label"]:
|
if name in ["apps", "app_label"]:
|
||||||
continue
|
continue
|
||||||
elif name in model._meta.original_attrs:
|
elif name in model._meta.original_attrs:
|
||||||
if name == "unique_together":
|
if name == "unique_together":
|
||||||
|
@ -164,17 +164,17 @@ class ModelState(object):
|
||||||
bases=self.bases,
|
bases=self.bases,
|
||||||
)
|
)
|
||||||
|
|
||||||
def render(self, app_cache):
|
def render(self, apps):
|
||||||
"Creates a Model object from our current state into the given app_cache"
|
"Creates a Model object from our current state into the given apps"
|
||||||
# First, make a Meta object
|
# First, make a Meta object
|
||||||
meta_contents = {'app_label': self.app_label, "app_cache": app_cache}
|
meta_contents = {'app_label': self.app_label, "apps": apps}
|
||||||
meta_contents.update(self.options)
|
meta_contents.update(self.options)
|
||||||
if "unique_together" in meta_contents:
|
if "unique_together" in meta_contents:
|
||||||
meta_contents["unique_together"] = list(meta_contents["unique_together"])
|
meta_contents["unique_together"] = list(meta_contents["unique_together"])
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
meta = type("Meta", tuple(), meta_contents)
|
||||||
# Then, work out our bases
|
# Then, work out our bases
|
||||||
bases = tuple(
|
bases = tuple(
|
||||||
(app_cache.get_model(*base.split(".", 1)) if isinstance(base, six.string_types) else base)
|
(apps.get_model(*base.split(".", 1)) if isinstance(base, six.string_types) else base)
|
||||||
for base in self.bases
|
for base in self.bases
|
||||||
)
|
)
|
||||||
if None in bases:
|
if None in bases:
|
||||||
|
|
|
@ -5,7 +5,7 @@ from importlib import import_module
|
||||||
import os
|
import os
|
||||||
import types
|
import types
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -69,7 +69,7 @@ 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_config = app_cache.get_app_config(self.migration.app_label)
|
app_config = apps.get_app_config(self.migration.app_label)
|
||||||
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
|
||||||
|
|
|
@ -5,7 +5,7 @@ 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 import app_cache
|
from django.apps import apps
|
||||||
from django.apps.base import MODELS_MODULE_NAME
|
from django.apps.base 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
|
||||||
|
@ -151,7 +151,7 @@ class ModelBase(type):
|
||||||
new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
|
new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
|
||||||
|
|
||||||
# Bail out early if we have already created this class.
|
# Bail out early if we have already created this class.
|
||||||
m = new_class._meta.app_cache.get_registered_model(new_class._meta.app_label, name)
|
m = new_class._meta.apps.get_registered_model(new_class._meta.app_label, name)
|
||||||
if m is not None:
|
if m is not None:
|
||||||
return m
|
return m
|
||||||
|
|
||||||
|
@ -273,12 +273,12 @@ class ModelBase(type):
|
||||||
|
|
||||||
new_class._prepare()
|
new_class._prepare()
|
||||||
|
|
||||||
new_class._meta.app_cache.register_model(new_class._meta.app_label, new_class)
|
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
|
||||||
# Because of the way imports happen (recursively), we may or may not be
|
# Because of the way imports happen (recursively), we may or may not be
|
||||||
# the first time this model tries to register with the framework. There
|
# the first time this model tries to register with the framework. There
|
||||||
# should only be one class for each model, so we always return the
|
# should only be one class for each model, so we always return the
|
||||||
# registered version.
|
# registered version.
|
||||||
return new_class._meta.app_cache.get_registered_model(new_class._meta.app_label, name)
|
return new_class._meta.apps.get_registered_model(new_class._meta.app_label, name)
|
||||||
|
|
||||||
def copy_managers(cls, base_managers):
|
def copy_managers(cls, base_managers):
|
||||||
# This is in-place sorting of an Options attribute, but that's fine.
|
# This is in-place sorting of an Options attribute, but that's fine.
|
||||||
|
@ -1065,7 +1065,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 = app_cache.get_model(*model_id)
|
model = apps.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
|
||||||
|
|
|
@ -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 import app_cache
|
from django.apps import apps
|
||||||
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 app_cache.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
|
return apps.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
|
||||||
|
|
||||||
|
|
||||||
class FieldDoesNotExist(Exception):
|
class FieldDoesNotExist(Exception):
|
||||||
|
@ -287,7 +287,7 @@ class Field(object):
|
||||||
def __reduce__(self):
|
def __reduce__(self):
|
||||||
"""
|
"""
|
||||||
Pickling should return the model._meta.fields instance of the field,
|
Pickling should return the model._meta.fields instance of the field,
|
||||||
not a new copy of that field. So, we use the app cache to load the
|
not a new copy of that field. So, we use the app registry to load the
|
||||||
model and then the field back.
|
model and then the field back.
|
||||||
"""
|
"""
|
||||||
if not hasattr(self, 'model'):
|
if not hasattr(self, 'model'):
|
||||||
|
@ -298,8 +298,8 @@ class Field(object):
|
||||||
# values - so, this is very close to normal pickle.
|
# values - so, this is very close to normal pickle.
|
||||||
return _empty, (self.__class__,), self.__dict__
|
return _empty, (self.__class__,), self.__dict__
|
||||||
if self.model._deferred:
|
if self.model._deferred:
|
||||||
# Deferred model will not be found from the app cache. This could
|
# Deferred model will not be found from the app registry. This
|
||||||
# be fixed by reconstructing the deferred model on unpickle.
|
# could be fixed by reconstructing the deferred model on unpickle.
|
||||||
raise RuntimeError("Fields of deferred models can't be reduced")
|
raise RuntimeError("Fields of deferred models can't be reduced")
|
||||||
return _load_field, (self.model._meta.app_label, self.model._meta.object_name,
|
return _load_field, (self.model._meta.app_label, self.model._meta.object_name,
|
||||||
self.name)
|
self.name)
|
||||||
|
|
|
@ -68,13 +68,13 @@ def add_lazy_relation(cls, field, relation, operation):
|
||||||
# string right away. If get_model returns None, it means that the related
|
# string right away. If get_model returns None, it means that the related
|
||||||
# model isn't loaded yet, so we need to pend the relation until the class
|
# model isn't loaded yet, so we need to pend the relation until the class
|
||||||
# is prepared.
|
# is prepared.
|
||||||
model = cls._meta.app_cache.get_registered_model(app_label, model_name)
|
model = cls._meta.apps.get_registered_model(app_label, model_name)
|
||||||
if model:
|
if model:
|
||||||
operation(field, model, cls)
|
operation(field, model, cls)
|
||||||
else:
|
else:
|
||||||
key = (app_label, model_name)
|
key = (app_label, model_name)
|
||||||
value = (cls, field, operation)
|
value = (cls, field, operation)
|
||||||
cls._meta.app_cache._pending_lookups.setdefault(key, []).append(value)
|
cls._meta.apps._pending_lookups.setdefault(key, []).append(value)
|
||||||
|
|
||||||
|
|
||||||
def do_pending_lookups(sender, **kwargs):
|
def do_pending_lookups(sender, **kwargs):
|
||||||
|
@ -82,7 +82,7 @@ def do_pending_lookups(sender, **kwargs):
|
||||||
Handle any pending relations to the sending model. Sent from class_prepared.
|
Handle any pending relations to the sending model. Sent from class_prepared.
|
||||||
"""
|
"""
|
||||||
key = (sender._meta.app_label, sender.__name__)
|
key = (sender._meta.app_label, sender.__name__)
|
||||||
for cls, field, operation in sender._meta.app_cache._pending_lookups.pop(key, []):
|
for cls, field, operation in sender._meta.apps._pending_lookups.pop(key, []):
|
||||||
operation(field, sender, cls)
|
operation(field, sender, cls)
|
||||||
|
|
||||||
signals.class_prepared.connect(do_pending_lookups)
|
signals.class_prepared.connect(do_pending_lookups)
|
||||||
|
@ -1493,7 +1493,7 @@ def create_many_to_many_intermediary_model(field, klass):
|
||||||
'unique_together': (from_, to),
|
'unique_together': (from_, to),
|
||||||
'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
|
'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to},
|
||||||
'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
|
'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to},
|
||||||
'app_cache': field.model._meta.app_cache,
|
'apps': field.model._meta.apps,
|
||||||
})
|
})
|
||||||
# Construct and return the new class.
|
# Construct and return the new class.
|
||||||
return type(str(name), (models.Model,), {
|
return type(str(name), (models.Model,), {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
|
|
||||||
warnings.warn(
|
warnings.warn(
|
||||||
"The utilities in django.db.models.loading are deprecated "
|
"The utilities in django.db.models.loading are deprecated "
|
||||||
|
@ -12,24 +12,24 @@ __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 = app_cache.get_apps
|
get_apps = apps.get_apps
|
||||||
get_app_package = app_cache.get_app_package
|
get_app_package = apps.get_app_package
|
||||||
get_app_path = app_cache.get_app_path
|
get_app_path = apps.get_app_path
|
||||||
get_app_paths = app_cache.get_app_paths
|
get_app_paths = apps.get_app_paths
|
||||||
get_app = app_cache.get_app
|
get_app = apps.get_app
|
||||||
get_models = app_cache.get_models
|
get_models = apps.get_models
|
||||||
get_model = app_cache.get_model
|
get_model = apps.get_model
|
||||||
register_models = app_cache.register_models
|
register_models = apps.register_models
|
||||||
load_app = app_cache.load_app
|
load_app = apps.load_app
|
||||||
app_cache_ready = app_cache.app_cache_ready
|
app_cache_ready = apps.ready
|
||||||
|
|
||||||
|
|
||||||
# This method doesn't return anything interesting in Django 1.6. Maintain it
|
# This method doesn't return anything interesting in Django 1.6. Maintain it
|
||||||
# just for backwards compatibility until this module is deprecated.
|
# just for backwards compatibility until this module is deprecated.
|
||||||
def get_app_errors():
|
def get_app_errors():
|
||||||
try:
|
try:
|
||||||
return app_cache.app_errors
|
return apps.app_errors
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
app_cache.populate_models()
|
apps.populate_models()
|
||||||
app_cache.app_errors = {}
|
apps.app_errors = {}
|
||||||
return app_cache.app_errors
|
return apps.app_errors
|
||||||
|
|
|
@ -5,7 +5,7 @@ import re
|
||||||
from bisect import bisect
|
from bisect import bisect
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -22,7 +22,7 @@ DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering',
|
||||||
'unique_together', 'permissions', 'get_latest_by',
|
'unique_together', 'permissions', 'get_latest_by',
|
||||||
'order_with_respect_to', 'app_label', 'db_tablespace',
|
'order_with_respect_to', 'app_label', 'db_tablespace',
|
||||||
'abstract', 'managed', 'proxy', 'swappable', 'auto_created',
|
'abstract', 'managed', 'proxy', 'swappable', 'auto_created',
|
||||||
'index_together', 'app_cache', 'default_permissions',
|
'index_together', 'apps', 'default_permissions',
|
||||||
'select_on_save')
|
'select_on_save')
|
||||||
|
|
||||||
|
|
||||||
|
@ -88,13 +88,13 @@ class Options(object):
|
||||||
# from *other* models. Needed for some admin checks. Internal use only.
|
# from *other* models. Needed for some admin checks. Internal use only.
|
||||||
self.related_fkey_lookups = []
|
self.related_fkey_lookups = []
|
||||||
|
|
||||||
# A custom AppCache to use, if you're making a separate model set.
|
# A custom app registry to use, if you're making a separate model set.
|
||||||
self.app_cache = app_cache
|
self.apps = apps
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def app_config(self):
|
def app_config(self):
|
||||||
# Don't go through get_app_config to avoid triggering imports.
|
# Don't go through get_app_config to avoid triggering imports.
|
||||||
return self.app_cache.app_configs.get(self.app_label)
|
return self.apps.app_configs.get(self.app_label)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def installed(self):
|
def installed(self):
|
||||||
|
@ -440,7 +440,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.app_cache_ready():
|
if apps.ready():
|
||||||
self._name_map = cache
|
self._name_map = cache
|
||||||
return cache
|
return cache
|
||||||
|
|
||||||
|
@ -516,7 +516,7 @@ class Options(object):
|
||||||
cache[obj] = model
|
cache[obj] = model
|
||||||
# Collect also objects which are in relation to some proxy child/parent of self.
|
# Collect also objects which are in relation to some proxy child/parent of self.
|
||||||
proxy_cache = cache.copy()
|
proxy_cache = cache.copy()
|
||||||
for klass in self.app_cache.get_models(include_auto_created=True, only_installed=False):
|
for klass in self.apps.get_models(include_auto_created=True, only_installed=False):
|
||||||
if not klass._meta.swapped:
|
if not klass._meta.swapped:
|
||||||
for f in klass._meta.local_fields:
|
for f in klass._meta.local_fields:
|
||||||
if f.rel and not isinstance(f.rel.to, six.string_types) and f.generate_reverse_relation:
|
if f.rel and not isinstance(f.rel.to, six.string_types) and f.generate_reverse_relation:
|
||||||
|
@ -559,14 +559,14 @@ class Options(object):
|
||||||
cache[obj] = parent
|
cache[obj] = parent
|
||||||
else:
|
else:
|
||||||
cache[obj] = model
|
cache[obj] = model
|
||||||
for klass in self.app_cache.get_models(only_installed=False):
|
for klass in self.apps.get_models(only_installed=False):
|
||||||
if not klass._meta.swapped:
|
if not klass._meta.swapped:
|
||||||
for f in klass._meta.local_many_to_many:
|
for f in klass._meta.local_many_to_many:
|
||||||
if (f.rel
|
if (f.rel
|
||||||
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.app_cache_ready():
|
if apps.ready():
|
||||||
self._related_many_to_many_cache = cache
|
self._related_many_to_many_cache = cache
|
||||||
return cache
|
return cache
|
||||||
|
|
||||||
|
|
|
@ -189,9 +189,9 @@ def deferred_class_factory(model, attrs):
|
||||||
proxy = True
|
proxy = True
|
||||||
app_label = model._meta.app_label
|
app_label = model._meta.app_label
|
||||||
|
|
||||||
# The app_cache wants a unique name for each model, otherwise the new class
|
# The app registry wants a unique name for each model, otherwise the new
|
||||||
# won't be created (we get an old one back). Therefore, we generate the
|
# class won't be created (we get an old one back). Therefore, we generate
|
||||||
# name using the passed in attrs. It's OK to reuse an existing class
|
# the name using the passed in attrs. It's OK to reuse an existing class
|
||||||
# object if the attrs are identical.
|
# object if the attrs are identical.
|
||||||
name = "%s_Deferred_%s" % (model.__name__, '_'.join(sorted(list(attrs))))
|
name = "%s_Deferred_%s" % (model.__name__, '_'.join(sorted(list(attrs))))
|
||||||
name = utils.truncate_name(name, 80, 32)
|
name = utils.truncate_name(name, 80, 32)
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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 = app_cache.get_model(app_label, object_name, only_installed=False)
|
sender = apps.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(
|
||||||
|
|
|
@ -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 django.apps import app_cache
|
from django.apps import apps
|
||||||
return [model for model in app_cache.get_models(app, include_auto_created=include_auto_created)
|
return [model for model in apps.get_models(app, include_auto_created=include_auto_created)
|
||||||
if self.allow_migrate(db, model)]
|
if self.allow_migrate(db, model)]
|
||||||
|
|
|
@ -5,7 +5,7 @@ from functools import partial
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
from inspect import getargspec, getcallargs
|
from inspect import getargspec, getcallargs
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.template.context import (BaseContext, Context, RequestContext, # NOQA: imported for backwards compatibility
|
from django.template.context import (BaseContext, Context, RequestContext, # NOQA: imported for backwards compatibility
|
||||||
ContextPopException)
|
ContextPopException)
|
||||||
|
@ -1306,7 +1306,7 @@ def get_templatetags_modules():
|
||||||
|
|
||||||
templatetags_modules_candidates = ['django.templatetags']
|
templatetags_modules_candidates = ['django.templatetags']
|
||||||
templatetags_modules_candidates += ['%s.templatetags' % app_config.name
|
templatetags_modules_candidates += ['%s.templatetags' % app_config.name
|
||||||
for app_config in app_cache.get_app_configs()]
|
for app_config in apps.get_app_configs()]
|
||||||
for templatetag_module in templatetags_modules_candidates:
|
for templatetag_module in templatetags_modules_candidates:
|
||||||
try:
|
try:
|
||||||
import_module(templatetag_module)
|
import_module(templatetag_module)
|
||||||
|
|
|
@ -6,7 +6,7 @@ packages.
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.template.base import TemplateDoesNotExist
|
from django.template.base import TemplateDoesNotExist
|
||||||
from django.template.loader import BaseLoader
|
from django.template.loader import BaseLoader
|
||||||
|
@ -17,7 +17,7 @@ from django.utils import six
|
||||||
if six.PY2:
|
if six.PY2:
|
||||||
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
|
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
|
||||||
app_template_dirs = []
|
app_template_dirs = []
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
template_dir = os.path.join(app_config.path, 'templates')
|
template_dir = os.path.join(app_config.path, 'templates')
|
||||||
if os.path.isdir(template_dir):
|
if os.path.isdir(template_dir):
|
||||||
if six.PY2:
|
if six.PY2:
|
||||||
|
|
|
@ -6,7 +6,7 @@ try:
|
||||||
except ImportError:
|
except ImportError:
|
||||||
resource_string = None
|
resource_string = None
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.template.base import TemplateDoesNotExist
|
from django.template.base import TemplateDoesNotExist
|
||||||
from django.template.loader import BaseLoader
|
from django.template.loader import BaseLoader
|
||||||
|
@ -24,7 +24,7 @@ class Loader(BaseLoader):
|
||||||
"""
|
"""
|
||||||
if resource_string is not None:
|
if resource_string is not None:
|
||||||
pkg_name = 'templates/' + template_name
|
pkg_name = 'templates/' + template_name
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
try:
|
try:
|
||||||
resource = resource_string(app_config.name, pkg_name)
|
resource = resource_string(app_config.name, pkg_name)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
|
@ -8,7 +8,7 @@ from copy import copy
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth import authenticate, login, logout, get_user_model
|
from django.contrib.auth import authenticate, login, logout, get_user_model
|
||||||
from django.core.handlers.base import BaseHandler
|
from django.core.handlers.base import BaseHandler
|
||||||
|
@ -390,7 +390,7 @@ class Client(RequestFactory):
|
||||||
"""
|
"""
|
||||||
Obtains the current session variables.
|
Obtains the current session variables.
|
||||||
"""
|
"""
|
||||||
if app_cache.has_app('django.contrib.sessions'):
|
if apps.has_app('django.contrib.sessions'):
|
||||||
engine = import_module(settings.SESSION_ENGINE)
|
engine = import_module(settings.SESSION_ENGINE)
|
||||||
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
|
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
|
||||||
if cookie:
|
if cookie:
|
||||||
|
@ -551,7 +551,7 @@ class Client(RequestFactory):
|
||||||
"""
|
"""
|
||||||
user = authenticate(**credentials)
|
user = authenticate(**credentials)
|
||||||
if (user and user.is_active and
|
if (user and user.is_active and
|
||||||
app_cache.has_app('django.contrib.sessions')):
|
apps.has_app('django.contrib.sessions')):
|
||||||
engine = import_module(settings.SESSION_ENGINE)
|
engine = import_module(settings.SESSION_ENGINE)
|
||||||
|
|
||||||
# Create a fake request that goes through request middleware
|
# Create a fake request that goes through request middleware
|
||||||
|
|
|
@ -9,7 +9,7 @@ import re
|
||||||
import unittest as real_unittest
|
import unittest as real_unittest
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -168,7 +168,7 @@ def build_test(label):
|
||||||
raise ValueError("Test label '%s' should be of the form app.TestCase "
|
raise ValueError("Test label '%s' should be of the form app.TestCase "
|
||||||
"or app.TestCase.test_method" % label)
|
"or app.TestCase.test_method" % label)
|
||||||
|
|
||||||
app_config = app_cache.get_app_config(parts[0])
|
app_config = apps.get_app_config(parts[0])
|
||||||
models_module = app_config.models_module
|
models_module = app_config.models_module
|
||||||
tests_module = get_tests(app_config)
|
tests_module = get_tests(app_config)
|
||||||
|
|
||||||
|
@ -237,10 +237,10 @@ class DjangoTestSuiteRunner(runner.DiscoverRunner):
|
||||||
if '.' in label:
|
if '.' in label:
|
||||||
suite.addTest(build_test(label))
|
suite.addTest(build_test(label))
|
||||||
else:
|
else:
|
||||||
app_config = app_cache.get_app_config(label)
|
app_config = apps.get_app_config(label)
|
||||||
suite.addTest(build_suite(app_config))
|
suite.addTest(build_suite(app_config))
|
||||||
else:
|
else:
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
suite.addTest(build_suite(app_config))
|
suite.addTest(build_suite(app_config))
|
||||||
|
|
||||||
if extra_tests:
|
if extra_tests:
|
||||||
|
|
|
@ -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 import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -732,13 +732,13 @@ class TransactionTestCase(SimpleTestCase):
|
||||||
"""Performs any pre-test setup. This includes:
|
"""Performs any pre-test setup. This includes:
|
||||||
|
|
||||||
* If the class has an 'available_apps' attribute, restricting the app
|
* If the class has an 'available_apps' attribute, restricting the app
|
||||||
cache to these applications, then firing post_migrate -- it must run
|
registry to these applications, then firing post_migrate -- it must
|
||||||
with the correct set of applications for the test case.
|
run with the correct set of applications for the test case.
|
||||||
* If the class has a 'fixtures' attribute, installing these fixtures.
|
* If the class has a 'fixtures' attribute, installing these fixtures.
|
||||||
"""
|
"""
|
||||||
super(TransactionTestCase, self)._pre_setup()
|
super(TransactionTestCase, self)._pre_setup()
|
||||||
if self.available_apps is not None:
|
if self.available_apps is not None:
|
||||||
app_cache.set_available_apps(self.available_apps)
|
apps.set_available_apps(self.available_apps)
|
||||||
setting_changed.send(sender=settings._wrapped.__class__,
|
setting_changed.send(sender=settings._wrapped.__class__,
|
||||||
setting='INSTALLED_APPS',
|
setting='INSTALLED_APPS',
|
||||||
value=self.available_apps,
|
value=self.available_apps,
|
||||||
|
@ -749,7 +749,7 @@ class TransactionTestCase(SimpleTestCase):
|
||||||
self._fixture_setup()
|
self._fixture_setup()
|
||||||
except Exception:
|
except Exception:
|
||||||
if self.available_apps is not None:
|
if self.available_apps is not None:
|
||||||
app_cache.unset_available_apps()
|
apps.unset_available_apps()
|
||||||
setting_changed.send(sender=settings._wrapped.__class__,
|
setting_changed.send(sender=settings._wrapped.__class__,
|
||||||
setting='INSTALLED_APPS',
|
setting='INSTALLED_APPS',
|
||||||
value=settings.INSTALLED_APPS,
|
value=settings.INSTALLED_APPS,
|
||||||
|
@ -809,7 +809,7 @@ class TransactionTestCase(SimpleTestCase):
|
||||||
conn.close()
|
conn.close()
|
||||||
finally:
|
finally:
|
||||||
if self.available_apps is not None:
|
if self.available_apps is not None:
|
||||||
app_cache.unset_available_apps()
|
apps.unset_available_apps()
|
||||||
setting_changed.send(sender=settings._wrapped.__class__,
|
setting_changed.send(sender=settings._wrapped.__class__,
|
||||||
setting='INSTALLED_APPS',
|
setting='INSTALLED_APPS',
|
||||||
value=settings.INSTALLED_APPS,
|
value=settings.INSTALLED_APPS,
|
||||||
|
|
|
@ -9,7 +9,7 @@ import warnings
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from xml.dom.minidom import parseString, Node
|
from xml.dom.minidom import parseString, Node
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings, UserSettingsHolder
|
from django.conf import settings, UserSettingsHolder
|
||||||
from django.core import mail
|
from django.core import mail
|
||||||
from django.core.signals import request_started
|
from django.core.signals import request_started
|
||||||
|
@ -229,9 +229,9 @@ class override_settings(object):
|
||||||
# in case it raises an exception because INSTALLED_APPS is invalid.
|
# in case it raises an exception because INSTALLED_APPS is invalid.
|
||||||
if 'INSTALLED_APPS' in self.options:
|
if 'INSTALLED_APPS' in self.options:
|
||||||
try:
|
try:
|
||||||
app_cache.set_installed_apps(self.options['INSTALLED_APPS'])
|
apps.set_installed_apps(self.options['INSTALLED_APPS'])
|
||||||
except Exception:
|
except Exception:
|
||||||
app_cache.unset_installed_apps()
|
apps.unset_installed_apps()
|
||||||
raise
|
raise
|
||||||
override = UserSettingsHolder(settings._wrapped)
|
override = UserSettingsHolder(settings._wrapped)
|
||||||
for key, new_value in self.options.items():
|
for key, new_value in self.options.items():
|
||||||
|
@ -244,7 +244,7 @@ class override_settings(object):
|
||||||
|
|
||||||
def disable(self):
|
def disable(self):
|
||||||
if 'INSTALLED_APPS' in self.options:
|
if 'INSTALLED_APPS' in self.options:
|
||||||
app_cache.unset_installed_apps()
|
apps.unset_installed_apps()
|
||||||
settings._wrapped = self.wrapped
|
settings._wrapped = self.wrapped
|
||||||
del self.wrapped
|
del self.wrapped
|
||||||
for key in self.options:
|
for key in self.options:
|
||||||
|
|
|
@ -36,7 +36,7 @@ import sys
|
||||||
import time
|
import time
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.signals import request_finished
|
from django.core.signals import request_finished
|
||||||
try:
|
try:
|
||||||
|
@ -90,7 +90,7 @@ def gen_filenames():
|
||||||
basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)),
|
basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)),
|
||||||
'conf', 'locale'),
|
'conf', 'locale'),
|
||||||
'locale']
|
'locale']
|
||||||
for app_config in reversed(list(app_cache.get_app_configs())):
|
for app_config in reversed(list(apps.get_app_configs())):
|
||||||
basedirs.append(os.path.join(app_config.path, 'locale'))
|
basedirs.append(os.path.join(app_config.path, 'locale'))
|
||||||
basedirs.extend(settings.LOCALE_PATHS)
|
basedirs.extend(settings.LOCALE_PATHS)
|
||||||
basedirs = [os.path.abspath(basedir) for basedir in basedirs
|
basedirs = [os.path.abspath(basedir) for basedir in basedirs
|
||||||
|
|
|
@ -58,10 +58,10 @@ def autodiscover_modules(*args, **kwargs):
|
||||||
registry. This register_to object must have a _registry instance variable
|
registry. This register_to object must have a _registry instance variable
|
||||||
to access it.
|
to access it.
|
||||||
"""
|
"""
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
|
|
||||||
register_to = kwargs.get('register_to')
|
register_to = kwargs.get('register_to')
|
||||||
for app_config in app_cache.get_app_configs():
|
for app_config in apps.get_app_configs():
|
||||||
# Attempt to import the app's module.
|
# Attempt to import the app's module.
|
||||||
try:
|
try:
|
||||||
if register_to:
|
if register_to:
|
||||||
|
|
|
@ -10,7 +10,7 @@ import gettext as gettext_module
|
||||||
from threading import local
|
from threading import local
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
from django.test.signals import setting_changed
|
from django.test.signals import setting_changed
|
||||||
from django.utils.encoding import force_str, force_text
|
from django.utils.encoding import force_str, force_text
|
||||||
|
@ -179,7 +179,7 @@ def translation(language):
|
||||||
res.merge(t)
|
res.merge(t)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
for app_config in reversed(list(app_cache.get_app_configs())):
|
for app_config in reversed(list(apps.get_app_configs())):
|
||||||
apppath = os.path.join(app_config.path, 'locale')
|
apppath = os.path.join(app_config.path, 'locale')
|
||||||
if os.path.isdir(apppath):
|
if os.path.isdir(apppath):
|
||||||
res = _merge(apppath)
|
res = _merge(apppath)
|
||||||
|
|
|
@ -4,7 +4,7 @@ import os
|
||||||
import gettext as gettext_module
|
import gettext as gettext_module
|
||||||
|
|
||||||
from django import http
|
from django import http
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.template import Context, Template
|
from django.template import Context, Template
|
||||||
from django.utils.translation import check_for_language, to_locale, get_language
|
from django.utils.translation import check_for_language, to_locale, get_language
|
||||||
|
@ -188,7 +188,7 @@ def render_javascript_catalog(catalog=None, plural=None):
|
||||||
|
|
||||||
def get_javascript_catalog(locale, domain, packages):
|
def get_javascript_catalog(locale, domain, packages):
|
||||||
default_locale = to_locale(settings.LANGUAGE_CODE)
|
default_locale = to_locale(settings.LANGUAGE_CODE)
|
||||||
app_configs = app_cache.get_app_configs()
|
app_configs = apps.get_app_configs()
|
||||||
allowable_packages = set(app_config.name for app_config in app_configs)
|
allowable_packages = set(app_config.name for app_config in app_configs)
|
||||||
allowable_packages.add('django.conf')
|
allowable_packages.add('django.conf')
|
||||||
packages = [p for p in packages if p in allowable_packages]
|
packages = [p for p in packages if p in allowable_packages]
|
||||||
|
|
|
@ -222,9 +222,7 @@ these changes.
|
||||||
* ``django.core.cache.get_cache`` will be removed. Add suitable entries
|
* ``django.core.cache.get_cache`` will be removed. Add suitable entries
|
||||||
to :setting:`CACHES` and use :data:`django.core.cache.caches` instead.
|
to :setting:`CACHES` and use :data:`django.core.cache.caches` instead.
|
||||||
|
|
||||||
* ``django.db.models.loading`` will be removed. Use the new application
|
* ``django.db.models.loading`` will be removed.
|
||||||
loading APIs instead. Several undocumented methods of the ``AppCache`` class
|
|
||||||
will also be removed.
|
|
||||||
|
|
||||||
* Passing callable arguments to querysets will no longer be possible.
|
* Passing callable arguments to querysets will no longer be possible.
|
||||||
|
|
||||||
|
|
|
@ -1,51 +0,0 @@
|
||||||
from __future__ import absolute_import
|
|
||||||
|
|
||||||
from django.apps import app_cache
|
|
||||||
from django.apps.cache import AppCache
|
|
||||||
from django.db import models
|
|
||||||
from django.test import TestCase
|
|
||||||
|
|
||||||
from .models import TotallyNormal, SoAlternative, new_app_cache
|
|
||||||
|
|
||||||
|
|
||||||
class AppCacheTests(TestCase):
|
|
||||||
|
|
||||||
def test_models_py(self):
|
|
||||||
"""
|
|
||||||
Tests that the models in the models.py file were loaded correctly.
|
|
||||||
"""
|
|
||||||
self.assertEqual(app_cache.get_model("app_cache", "TotallyNormal"), TotallyNormal)
|
|
||||||
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", "SoAlternative"), SoAlternative)
|
|
||||||
|
|
||||||
def test_dynamic_load(self):
|
|
||||||
"""
|
|
||||||
Makes a new model at runtime and ensures it goes into the right place.
|
|
||||||
"""
|
|
||||||
old_models = app_cache.get_models(app_cache.get_app_config("app_cache").models_module)
|
|
||||||
# Construct a new model in a new app cache
|
|
||||||
body = {}
|
|
||||||
new_app_cache = AppCache()
|
|
||||||
meta_contents = {
|
|
||||||
'app_label': "app_cache",
|
|
||||||
'app_cache': new_app_cache,
|
|
||||||
}
|
|
||||||
meta = type("Meta", tuple(), meta_contents)
|
|
||||||
body['Meta'] = meta
|
|
||||||
body['__module__'] = TotallyNormal.__module__
|
|
||||||
temp_model = type("SouthPonies", (models.Model,), body)
|
|
||||||
# Make sure it appeared in the right place!
|
|
||||||
self.assertEqual(
|
|
||||||
old_models,
|
|
||||||
app_cache.get_models(app_cache.get_app_config("app_cache").models_module),
|
|
||||||
)
|
|
||||||
self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model)
|
|
||||||
|
|
||||||
def test_singleton_master(self):
|
|
||||||
"""
|
|
||||||
Ensures that only one master app cache can exist.
|
|
||||||
"""
|
|
||||||
with self.assertRaises(RuntimeError):
|
|
||||||
AppCache(master=True)
|
|
|
@ -3,7 +3,7 @@ from __future__ import unicode_literals
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from django.utils._os import upath
|
from django.utils._os import upath
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
|
@ -17,11 +17,11 @@ class EggLoadingTest(TestCase):
|
||||||
|
|
||||||
# The models need to be removed after the test in order to prevent bad
|
# The models need to be removed after the test in order to prevent bad
|
||||||
# interactions with the flush operation in other tests.
|
# interactions with the flush operation in other tests.
|
||||||
self._old_models = app_cache.all_models['app_loading'].copy()
|
self._old_models = apps.all_models['app_loading'].copy()
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
app_cache.all_models['app_loading'] = self._old_models
|
apps.all_models['app_loading'] = self._old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
sys.path = self.old_path
|
sys.path = self.old_path
|
||||||
|
|
||||||
|
@ -30,7 +30,7 @@ class EggLoadingTest(TestCase):
|
||||||
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)
|
||||||
with self.settings(INSTALLED_APPS=['app_with_models']):
|
with self.settings(INSTALLED_APPS=['app_with_models']):
|
||||||
models_module = app_cache.get_app_config('app_with_models').models_module
|
models_module = apps.get_app_config('app_with_models').models_module
|
||||||
self.assertIsNotNone(models_module)
|
self.assertIsNotNone(models_module)
|
||||||
|
|
||||||
def test_egg2(self):
|
def test_egg2(self):
|
||||||
|
@ -38,7 +38,7 @@ class EggLoadingTest(TestCase):
|
||||||
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)
|
||||||
with self.settings(INSTALLED_APPS=['app_no_models']):
|
with self.settings(INSTALLED_APPS=['app_no_models']):
|
||||||
models_module = app_cache.get_app_config('app_no_models').models_module
|
models_module = apps.get_app_config('app_no_models').models_module
|
||||||
self.assertIsNone(models_module)
|
self.assertIsNone(models_module)
|
||||||
|
|
||||||
def test_egg3(self):
|
def test_egg3(self):
|
||||||
|
@ -46,7 +46,7 @@ class EggLoadingTest(TestCase):
|
||||||
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)
|
||||||
with self.settings(INSTALLED_APPS=['omelet.app_with_models']):
|
with self.settings(INSTALLED_APPS=['omelet.app_with_models']):
|
||||||
models_module = app_cache.get_app_config('app_with_models').models_module
|
models_module = apps.get_app_config('app_with_models').models_module
|
||||||
self.assertIsNotNone(models_module)
|
self.assertIsNotNone(models_module)
|
||||||
|
|
||||||
def test_egg4(self):
|
def test_egg4(self):
|
||||||
|
@ -54,7 +54,7 @@ class EggLoadingTest(TestCase):
|
||||||
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)
|
||||||
with self.settings(INSTALLED_APPS=['omelet.app_no_models']):
|
with self.settings(INSTALLED_APPS=['omelet.app_no_models']):
|
||||||
models_module = app_cache.get_app_config('app_no_models').models_module
|
models_module = apps.get_app_config('app_no_models').models_module
|
||||||
self.assertIsNone(models_module)
|
self.assertIsNone(models_module)
|
||||||
|
|
||||||
def test_egg5(self):
|
def test_egg5(self):
|
||||||
|
@ -73,26 +73,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(
|
||||||
app_cache.get_model("not_installed", "NotInstalledModel"), None)
|
apps.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(
|
||||||
app_cache.get_model(
|
apps.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.assertNotIn(
|
self.assertNotIn(
|
||||||
"NotInstalledModel",
|
"NotInstalledModel",
|
||||||
[m.__name__ for m in app_cache.get_models()])
|
[m.__name__ for m in apps.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(app_cache.get_models(self.not_installed_module), [])
|
self.assertEqual(apps.get_models(self.not_installed_module), [])
|
||||||
|
|
||||||
def test_get_models_with_not_installed(self):
|
def test_get_models_with_not_installed(self):
|
||||||
self.assertIn(
|
self.assertIn(
|
||||||
"NotInstalledModel",
|
"NotInstalledModel",
|
||||||
[m.__name__ for m in app_cache.get_models(only_installed=False)])
|
[m.__name__ for m in apps.get_models(only_installed=False)])
|
||||||
|
|
||||||
|
|
||||||
class NotInstalledModelsTest(TestCase):
|
class NotInstalledModelsTest(TestCase):
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
# We're testing app cache presence on load, so this is handy.
|
# We're testing app registry presence on load, so this is handy.
|
||||||
|
|
||||||
new_app_cache = AppCache()
|
new_apps = Apps()
|
||||||
|
|
||||||
|
|
||||||
class TotallyNormal(models.Model):
|
class TotallyNormal(models.Model):
|
||||||
|
@ -14,4 +14,4 @@ class SoAlternative(models.Model):
|
||||||
name = models.CharField(max_length=255)
|
name = models.CharField(max_length=255)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
|
@ -0,0 +1,51 @@
|
||||||
|
from __future__ import absolute_import
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.apps.registry import Apps
|
||||||
|
from django.db import models
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from .models import TotallyNormal, SoAlternative, new_apps
|
||||||
|
|
||||||
|
|
||||||
|
class AppsTests(TestCase):
|
||||||
|
|
||||||
|
def test_models_py(self):
|
||||||
|
"""
|
||||||
|
Tests that the models in the models.py file were loaded correctly.
|
||||||
|
"""
|
||||||
|
self.assertEqual(apps.get_model("apps", "TotallyNormal"), TotallyNormal)
|
||||||
|
self.assertEqual(apps.get_model("apps", "SoAlternative"), None)
|
||||||
|
|
||||||
|
self.assertEqual(new_apps.get_model("apps", "TotallyNormal"), None)
|
||||||
|
self.assertEqual(new_apps.get_model("apps", "SoAlternative"), SoAlternative)
|
||||||
|
|
||||||
|
def test_dynamic_load(self):
|
||||||
|
"""
|
||||||
|
Makes a new model at runtime and ensures it goes into the right place.
|
||||||
|
"""
|
||||||
|
old_models = apps.get_models(apps.get_app_config("apps").models_module)
|
||||||
|
# Construct a new model in a new app registry
|
||||||
|
body = {}
|
||||||
|
new_apps = Apps()
|
||||||
|
meta_contents = {
|
||||||
|
'app_label': "apps",
|
||||||
|
'apps': new_apps,
|
||||||
|
}
|
||||||
|
meta = type("Meta", tuple(), meta_contents)
|
||||||
|
body['Meta'] = meta
|
||||||
|
body['__module__'] = TotallyNormal.__module__
|
||||||
|
temp_model = type("SouthPonies", (models.Model,), body)
|
||||||
|
# Make sure it appeared in the right place!
|
||||||
|
self.assertEqual(
|
||||||
|
old_models,
|
||||||
|
apps.get_models(apps.get_app_config("apps").models_module),
|
||||||
|
)
|
||||||
|
self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
|
||||||
|
|
||||||
|
def test_singleton_master(self):
|
||||||
|
"""
|
||||||
|
Ensures that only one master registry can exist.
|
||||||
|
"""
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
Apps(master=True)
|
|
@ -5,7 +5,7 @@ from django.utils import six
|
||||||
|
|
||||||
|
|
||||||
# The models definitions below used to crash. Generating models dynamically
|
# The models definitions below used to crash. Generating models dynamically
|
||||||
# at runtime is a bad idea because it pollutes the app cache. This doesn't
|
# at runtime is a bad idea because it pollutes the app registry. This doesn't
|
||||||
# integrate well with the test suite but at least it prevents regressions.
|
# integrate well with the test suite but at least it prevents regressions.
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -5,7 +5,7 @@ import os
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.core.management import ManagementUtility
|
from django.core.management import ManagementUtility
|
||||||
from django.utils.six import StringIO
|
from django.utils.six import StringIO
|
||||||
|
|
||||||
|
@ -85,6 +85,6 @@ class BashCompletionTests(unittest.TestCase):
|
||||||
self._user_input('django-admin.py sqlall a')
|
self._user_input('django-admin.py sqlall a')
|
||||||
output = self._run_autocomplete()
|
output = self._run_autocomplete()
|
||||||
a_labels = sorted(app_config.label
|
a_labels = sorted(app_config.label
|
||||||
for app_config in app_cache.get_app_configs()
|
for app_config in apps.get_app_configs()
|
||||||
if app_config.label.startswith('a'))
|
if app_config.label.startswith('a'))
|
||||||
self.assertEqual(output, a_labels)
|
self.assertEqual(output, a_labels)
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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)
|
||||||
|
@ -17,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 = app_cache.get_app_config('commands_sql').models_module
|
app = apps.get_app_config('commands_sql').models_module
|
||||||
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)
|
||||||
|
@ -26,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 = app_cache.get_app_config('commands_sql').models_module
|
app = apps.get_app_config('commands_sql').models_module
|
||||||
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)
|
||||||
|
@ -35,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 = app_cache.get_app_config('commands_sql').models_module
|
app = apps.get_app_config('commands_sql').models_module
|
||||||
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 = app_cache.get_app_config('commands_sql').models_module
|
app = apps.get_app_config('commands_sql').models_module
|
||||||
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 = app_cache.get_app_config('commands_sql').models_module
|
app = apps.get_app_config('commands_sql').models_module
|
||||||
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)
|
||||||
|
@ -69,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 = app_cache.get_app_config('commands_sql').models_module
|
app = apps.get_app_config('commands_sql').models_module
|
||||||
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,
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
@ -61,7 +61,7 @@ class ContentTypesViewsTests(TestCase):
|
||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = 'a model created on the fly'
|
verbose_name = 'a model created on the fly'
|
||||||
app_label = 'my_great_app'
|
app_label = 'my_great_app'
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
ct = ContentType.objects.get_for_model(ModelCreatedOnTheFly)
|
ct = ContentType.objects.get_for_model(ModelCreatedOnTheFly)
|
||||||
self.assertEqual(ct.app_label, 'my_great_app')
|
self.assertEqual(ct.app_label, 'my_great_app')
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import unicode_literals
|
||||||
|
|
||||||
from operator import attrgetter
|
from operator import attrgetter
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -102,7 +102,7 @@ class DeferRegressionTest(TestCase):
|
||||||
klasses = set(
|
klasses = set(
|
||||||
map(
|
map(
|
||||||
attrgetter("__name__"),
|
attrgetter("__name__"),
|
||||||
app_cache.get_models(app_cache.get_app_config("defer_regress").models_module)
|
apps.get_models(apps.get_app_config("defer_regress").models_module)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.assertIn("Child", klasses)
|
self.assertIn("Child", klasses)
|
||||||
|
@ -110,13 +110,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 app_cache.get_models(app_cache.get_app_config("defer_regress").models_module)))
|
k._deferred for k in apps.get_models(apps.get_app_config("defer_regress").models_module)))
|
||||||
|
|
||||||
klasses_with_deferred = set(
|
klasses_with_deferred = set(
|
||||||
map(
|
map(
|
||||||
attrgetter("__name__"),
|
attrgetter("__name__"),
|
||||||
app_cache.get_models(
|
apps.get_models(
|
||||||
app_cache.get_app_config("defer_regress").models_module, include_deferred=True
|
apps.get_app_config("defer_regress").models_module, include_deferred=True
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
@ -125,8 +125,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 app_cache.get_models(
|
k._deferred for k in apps.get_models(
|
||||||
app_cache.get_app_config("defer_regress").models_module, include_deferred=True))
|
apps.get_app_config("defer_regress").models_module, include_deferred=True))
|
||||||
)
|
)
|
||||||
|
|
||||||
@override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer')
|
@override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer')
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.core.management.validation import get_validation_errors
|
from django.core.management.validation import get_validation_errors
|
||||||
from django.test import override_settings
|
from django.test import override_settings
|
||||||
from django.utils.six import StringIO
|
from django.utils.six import StringIO
|
||||||
|
@ -32,7 +32,7 @@ class InvalidModelTestCase(unittest.TestCase):
|
||||||
TEST_SWAPPED_MODEL_BAD_MODEL='not_an_app.Target',
|
TEST_SWAPPED_MODEL_BAD_MODEL='not_an_app.Target',
|
||||||
)
|
)
|
||||||
def test_invalid_models(self):
|
def test_invalid_models(self):
|
||||||
module = app_cache.get_app_config("invalid_models").models_module
|
module = apps.get_app_config("invalid_models").models_module
|
||||||
get_validation_errors(self.stdout, module)
|
get_validation_errors(self.stdout, module)
|
||||||
|
|
||||||
self.stdout.seek(0)
|
self.stdout.seek(0)
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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, override_settings
|
from django.test import TestCase, override_settings
|
||||||
|
@ -110,7 +110,7 @@ class ManagersRegressionTests(TestCase):
|
||||||
def test_swappable_manager(self):
|
def test_swappable_manager(self):
|
||||||
# The models need to be removed after the test in order to prevent bad
|
# The models need to be removed after the test in order to prevent bad
|
||||||
# interactions with the flush operation in other tests.
|
# interactions with the flush operation in other tests.
|
||||||
_old_models = app_cache.app_configs['managers_regress'].models.copy()
|
_old_models = apps.app_configs['managers_regress'].models.copy()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
class SwappableModel(models.Model):
|
class SwappableModel(models.Model):
|
||||||
|
@ -126,15 +126,15 @@ 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:
|
||||||
app_cache.app_configs['managers_regress'].models = _old_models
|
apps.app_configs['managers_regress'].models = _old_models
|
||||||
app_cache.all_models['managers_regress'] = _old_models
|
apps.all_models['managers_regress'] = _old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
@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):
|
||||||
# The models need to be removed after the test in order to prevent bad
|
# The models need to be removed after the test in order to prevent bad
|
||||||
# interactions with the flush operation in other tests.
|
# interactions with the flush operation in other tests.
|
||||||
_old_models = app_cache.app_configs['managers_regress'].models.copy()
|
_old_models = apps.app_configs['managers_regress'].models.copy()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
class SwappableModel(models.Model):
|
class SwappableModel(models.Model):
|
||||||
|
@ -154,15 +154,15 @@ 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:
|
||||||
app_cache.app_configs['managers_regress'].models = _old_models
|
apps.app_configs['managers_regress'].models = _old_models
|
||||||
app_cache.all_models['managers_regress'] = _old_models
|
apps.all_models['managers_regress'] = _old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
@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):
|
||||||
# The models need to be removed after the test in order to prevent bad
|
# The models need to be removed after the test in order to prevent bad
|
||||||
# interactions with the flush operation in other tests.
|
# interactions with the flush operation in other tests.
|
||||||
_old_models = app_cache.app_configs['managers_regress'].models.copy()
|
_old_models = apps.app_configs['managers_regress'].models.copy()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
class SwappableModel(models.Model):
|
class SwappableModel(models.Model):
|
||||||
|
@ -182,9 +182,9 @@ 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:
|
||||||
app_cache.app_configs['managers_regress'].models = _old_models
|
apps.app_configs['managers_regress'].models = _old_models
|
||||||
app_cache.all_models['managers_regress'] = _old_models
|
apps.all_models['managers_regress'] = _old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
def test_regress_3871(self):
|
def test_regress_3871(self):
|
||||||
related = RelatedModel.objects.create()
|
related = RelatedModel.objects.create()
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.encoding import python_2_unicode_compatible
|
from django.utils.encoding import python_2_unicode_compatible
|
||||||
|
|
||||||
|
@ -12,7 +12,7 @@ class UnicodeModel(models.Model):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
# Disable auto loading of this model as we load it on our own
|
# Disable auto loading of this model as we load it on our own
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
verbose_name = 'úñí©óðé µóðéø'
|
verbose_name = 'úñí©óðé µóðéø'
|
||||||
verbose_name_plural = 'úñí©óðé µóðéøß'
|
verbose_name_plural = 'úñí©óðé µóðéøß'
|
||||||
|
|
||||||
|
@ -32,4 +32,4 @@ class UnserializableModel(models.Model):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
# Disable auto loading of this model as we load it on our own
|
# Disable auto loading of this model as we load it on our own
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
|
@ -5,7 +5,7 @@ import codecs
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.core.management import call_command, CommandError
|
from django.core.management import call_command, CommandError
|
||||||
from django.test import override_settings
|
from django.test import override_settings
|
||||||
from django.utils import six
|
from django.utils import six
|
||||||
|
@ -131,12 +131,12 @@ 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_models = app_cache.app_configs['migrations'].models.copy()
|
self._old_models = apps.app_configs['migrations'].models.copy()
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
app_cache.app_configs['migrations'].models = self._old_models
|
apps.app_configs['migrations'].models = self._old_models
|
||||||
app_cache.all_models['migrations'] = self._old_models
|
apps.all_models['migrations'] = self._old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
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")
|
||||||
app_cache.register_model('migrations', UnicodeModel)
|
apps.register_model('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.
|
||||||
app_cache.register_model('migrations', UnserializableModel)
|
apps.register_model('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}):
|
||||||
|
|
|
@ -43,7 +43,7 @@ class LoaderTests(TestCase):
|
||||||
def test_load(self):
|
def test_load(self):
|
||||||
"""
|
"""
|
||||||
Makes sure the loader can load the migrations for the test apps,
|
Makes sure the loader can load the migrations for the test apps,
|
||||||
and then render them out to a new AppCache.
|
and then render them out to a new Apps.
|
||||||
"""
|
"""
|
||||||
# Load and test the plan
|
# Load and test the plan
|
||||||
migration_loader = MigrationLoader(connection)
|
migration_loader = MigrationLoader(connection)
|
||||||
|
|
|
@ -203,8 +203,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():
|
||||||
new_app_cache = new_state.render()
|
new_apps = new_state.render()
|
||||||
Pony = new_app_cache.get_model("test_adflmm", "Pony")
|
Pony = new_apps.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)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.db.migrations.state import ProjectState, ModelState, InvalidBasesError
|
from django.db.migrations.state import ProjectState, ModelState, InvalidBasesError
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
@ -11,10 +11,10 @@ class StateTests(TestCase):
|
||||||
|
|
||||||
def test_create(self):
|
def test_create(self):
|
||||||
"""
|
"""
|
||||||
Tests making a ProjectState from an AppCache
|
Tests making a ProjectState from an Apps
|
||||||
"""
|
"""
|
||||||
|
|
||||||
new_app_cache = AppCache()
|
new_apps = Apps()
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
name = models.CharField(max_length=255)
|
name = models.CharField(max_length=255)
|
||||||
|
@ -23,13 +23,13 @@ class StateTests(TestCase):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
unique_together = ["name", "bio"]
|
unique_together = ["name", "bio"]
|
||||||
|
|
||||||
class AuthorProxy(Author):
|
class AuthorProxy(Author):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
proxy = True
|
proxy = True
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
|
||||||
|
@ -40,11 +40,11 @@ class StateTests(TestCase):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
verbose_name = "tome"
|
verbose_name = "tome"
|
||||||
db_table = "test_tome"
|
db_table = "test_tome"
|
||||||
|
|
||||||
project_state = ProjectState.from_app_cache(new_app_cache)
|
project_state = ProjectState.from_apps(new_apps)
|
||||||
author_state = project_state.models['migrations', 'author']
|
author_state = project_state.models['migrations', 'author']
|
||||||
author_proxy_state = project_state.models['migrations', 'authorproxy']
|
author_proxy_state = project_state.models['migrations', 'authorproxy']
|
||||||
book_state = project_state.models['migrations', 'book']
|
book_state = project_state.models['migrations', 'book']
|
||||||
|
@ -75,7 +75,7 @@ class StateTests(TestCase):
|
||||||
|
|
||||||
def test_render(self):
|
def test_render(self):
|
||||||
"""
|
"""
|
||||||
Tests rendering a ProjectState into an AppCache.
|
Tests rendering a ProjectState into an Apps.
|
||||||
"""
|
"""
|
||||||
project_state = ProjectState()
|
project_state = ProjectState()
|
||||||
project_state.add_model_state(ModelState(
|
project_state.add_model_state(ModelState(
|
||||||
|
@ -90,9 +90,9 @@ class StateTests(TestCase):
|
||||||
None,
|
None,
|
||||||
))
|
))
|
||||||
|
|
||||||
new_app_cache = project_state.render()
|
new_apps = project_state.render()
|
||||||
self.assertEqual(new_app_cache.get_model("migrations", "Tag")._meta.get_field_by_name("name")[0].max_length, 100)
|
self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field_by_name("name")[0].max_length, 100)
|
||||||
self.assertEqual(new_app_cache.get_model("migrations", "Tag")._meta.get_field_by_name("hidden")[0].null, False)
|
self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field_by_name("hidden")[0].null, False)
|
||||||
|
|
||||||
def test_render_model_inheritance(self):
|
def test_render_model_inheritance(self):
|
||||||
class Book(models.Model):
|
class Book(models.Model):
|
||||||
|
@ -100,90 +100,90 @@ class StateTests(TestCase):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
class Novel(Book):
|
class Novel(Book):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
# First, test rendering individually
|
# First, test rendering individually
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
# We shouldn't be able to render yet
|
# We shouldn't be able to render yet
|
||||||
ms = ModelState.from_model(Novel)
|
ms = ModelState.from_model(Novel)
|
||||||
with self.assertRaises(InvalidBasesError):
|
with self.assertRaises(InvalidBasesError):
|
||||||
ms.render(app_cache)
|
ms.render(apps)
|
||||||
|
|
||||||
# Once the parent model is in the app cache, it should be fine
|
# Once the parent model is in the app registry, it should be fine
|
||||||
ModelState.from_model(Book).render(app_cache)
|
ModelState.from_model(Book).render(apps)
|
||||||
ModelState.from_model(Novel).render(app_cache)
|
ModelState.from_model(Novel).render(apps)
|
||||||
|
|
||||||
def test_render_model_with_multiple_inheritance(self):
|
def test_render_model_with_multiple_inheritance(self):
|
||||||
class Foo(models.Model):
|
class Foo(models.Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
class Bar(models.Model):
|
class Bar(models.Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
class FooBar(Foo, Bar):
|
class FooBar(Foo, Bar):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
app_cache = AppCache()
|
apps = Apps()
|
||||||
|
|
||||||
# We shouldn't be able to render yet
|
# We shouldn't be able to render yet
|
||||||
ms = ModelState.from_model(FooBar)
|
ms = ModelState.from_model(FooBar)
|
||||||
with self.assertRaises(InvalidBasesError):
|
with self.assertRaises(InvalidBasesError):
|
||||||
ms.render(app_cache)
|
ms.render(apps)
|
||||||
|
|
||||||
# Once the parent models are in the app cache, it should be fine
|
# Once the parent models are in the app registry, it should be fine
|
||||||
ModelState.from_model(Foo).render(app_cache)
|
ModelState.from_model(Foo).render(apps)
|
||||||
ModelState.from_model(Bar).render(app_cache)
|
ModelState.from_model(Bar).render(apps)
|
||||||
ModelState.from_model(FooBar).render(app_cache)
|
ModelState.from_model(FooBar).render(apps)
|
||||||
|
|
||||||
def test_render_project_dependencies(self):
|
def test_render_project_dependencies(self):
|
||||||
"""
|
"""
|
||||||
Tests that the ProjectState render method correctly renders models
|
Tests that the ProjectState render method correctly renders models
|
||||||
to account for inter-model base dependencies.
|
to account for inter-model base dependencies.
|
||||||
"""
|
"""
|
||||||
new_app_cache = AppCache()
|
new_apps = Apps()
|
||||||
|
|
||||||
class A(models.Model):
|
class A(models.Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
class B(A):
|
class B(A):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
class C(B):
|
class C(B):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
class D(A):
|
class D(A):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
class E(B):
|
class E(B):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
proxy = True
|
proxy = True
|
||||||
|
|
||||||
class F(D):
|
class F(D):
|
||||||
class Meta:
|
class Meta:
|
||||||
app_label = "migrations"
|
app_label = "migrations"
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
proxy = True
|
proxy = True
|
||||||
|
|
||||||
# Make a ProjectState and render it
|
# Make a ProjectState and render it
|
||||||
|
@ -194,8 +194,8 @@ class StateTests(TestCase):
|
||||||
project_state.add_model_state(ModelState.from_model(D))
|
project_state.add_model_state(ModelState.from_model(D))
|
||||||
project_state.add_model_state(ModelState.from_model(E))
|
project_state.add_model_state(ModelState.from_model(E))
|
||||||
project_state.add_model_state(ModelState.from_model(F))
|
project_state.add_model_state(ModelState.from_model(F))
|
||||||
final_app_cache = project_state.render()
|
final_apps = project_state.render()
|
||||||
self.assertEqual(len(final_app_cache.get_models()), 6)
|
self.assertEqual(len(final_apps.get_models()), 6)
|
||||||
|
|
||||||
# Now make an invalid ProjectState and make sure it fails
|
# Now make an invalid ProjectState and make sure it fails
|
||||||
project_state = ProjectState()
|
project_state = ProjectState()
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
|
||||||
|
|
||||||
|
@ -6,5 +6,5 @@ class NoModelTests(TestCase):
|
||||||
|
|
||||||
def test_no_models(self):
|
def test_no_models(self):
|
||||||
"""Test that it's possible to load an app with no models.py file."""
|
"""Test that it's possible to load an app with no models.py file."""
|
||||||
app_config = app_cache.get_app_config('no_models')
|
app_config = apps.get_app_config('no_models')
|
||||||
self.assertIsNone(app_config.models_module)
|
self.assertIsNone(app_config.models_module)
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -155,7 +155,7 @@ class ProxyModelTests(TestCase):
|
||||||
def test_swappable(self):
|
def test_swappable(self):
|
||||||
# The models need to be removed after the test in order to prevent bad
|
# The models need to be removed after the test in order to prevent bad
|
||||||
# interactions with the flush operation in other tests.
|
# interactions with the flush operation in other tests.
|
||||||
_old_models = app_cache.app_configs['proxy_models'].models.copy()
|
_old_models = apps.app_configs['proxy_models'].models.copy()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
class SwappableModel(models.Model):
|
class SwappableModel(models.Model):
|
||||||
|
@ -173,9 +173,9 @@ class ProxyModelTests(TestCase):
|
||||||
class Meta:
|
class Meta:
|
||||||
proxy = True
|
proxy = True
|
||||||
finally:
|
finally:
|
||||||
app_cache.app_configs['proxy_models'].models = _old_models
|
apps.app_configs['proxy_models'].models = _old_models
|
||||||
app_cache.all_models['proxy_models'] = _old_models
|
apps.all_models['proxy_models'] = _old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
def test_myperson_manager(self):
|
def test_myperson_manager(self):
|
||||||
Person.objects.create(name="fred")
|
Person.objects.create(name="fred")
|
||||||
|
|
|
@ -80,13 +80,13 @@ def get_test_modules():
|
||||||
|
|
||||||
|
|
||||||
def get_installed():
|
def get_installed():
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
return [app_config.name for app_config in app_cache.get_app_configs()]
|
return [app_config.name for app_config in apps.get_app_configs()]
|
||||||
|
|
||||||
|
|
||||||
def setup(verbosity, test_labels):
|
def setup(verbosity, test_labels):
|
||||||
import django
|
import django
|
||||||
from django.apps import app_cache, AppConfig
|
from django.apps import apps, AppConfig
|
||||||
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)
|
||||||
app_cache.populate_models()
|
apps.populate_models()
|
||||||
|
|
||||||
# Load all the test model apps.
|
# Load all the test model apps.
|
||||||
test_modules = get_test_modules()
|
test_modules = get_test_modules()
|
||||||
|
@ -168,9 +168,9 @@ def setup(verbosity, test_labels):
|
||||||
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)
|
||||||
app_config = AppConfig.create(module_label)
|
app_config = AppConfig.create(module_label)
|
||||||
app_config.import_models(app_cache.all_models[app_config.label])
|
app_config.import_models(apps.all_models[app_config.label])
|
||||||
app_cache.app_configs[app_config.label] = app_config
|
apps.app_configs[app_config.label] = app_config
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
return state
|
return state
|
||||||
|
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
# Because we want to test creation and deletion of these as separate things,
|
# Because we want to test creation and deletion of these as separate things,
|
||||||
# these models are all inserted into a separate AppCache so the main test
|
# these models are all inserted into a separate Apps so the main test
|
||||||
# runner doesn't migrate them.
|
# runner doesn't migrate them.
|
||||||
|
|
||||||
new_app_cache = AppCache()
|
new_apps = Apps()
|
||||||
|
|
||||||
|
|
||||||
class Author(models.Model):
|
class Author(models.Model):
|
||||||
|
@ -13,14 +13,14 @@ class Author(models.Model):
|
||||||
height = models.PositiveIntegerField(null=True, blank=True)
|
height = models.PositiveIntegerField(null=True, blank=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
|
|
||||||
class AuthorWithM2M(models.Model):
|
class AuthorWithM2M(models.Model):
|
||||||
name = models.CharField(max_length=255)
|
name = models.CharField(max_length=255)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
|
|
||||||
class Book(models.Model):
|
class Book(models.Model):
|
||||||
|
@ -30,7 +30,7 @@ class Book(models.Model):
|
||||||
# tags = models.ManyToManyField("Tag", related_name="books")
|
# tags = models.ManyToManyField("Tag", related_name="books")
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
|
|
||||||
class BookWithM2M(models.Model):
|
class BookWithM2M(models.Model):
|
||||||
|
@ -40,7 +40,7 @@ class BookWithM2M(models.Model):
|
||||||
tags = models.ManyToManyField("TagM2MTest", related_name="books")
|
tags = models.ManyToManyField("TagM2MTest", related_name="books")
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
|
|
||||||
class BookWithSlug(models.Model):
|
class BookWithSlug(models.Model):
|
||||||
|
@ -50,7 +50,7 @@ class BookWithSlug(models.Model):
|
||||||
slug = models.CharField(max_length=20, unique=True)
|
slug = models.CharField(max_length=20, unique=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
db_table = "schema_book"
|
db_table = "schema_book"
|
||||||
|
|
||||||
|
|
||||||
|
@ -59,7 +59,7 @@ class Tag(models.Model):
|
||||||
slug = models.SlugField(unique=True)
|
slug = models.SlugField(unique=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
|
|
||||||
class TagM2MTest(models.Model):
|
class TagM2MTest(models.Model):
|
||||||
|
@ -67,7 +67,7 @@ class TagM2MTest(models.Model):
|
||||||
slug = models.SlugField(unique=True)
|
slug = models.SlugField(unique=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
||||||
|
|
||||||
class TagIndexed(models.Model):
|
class TagIndexed(models.Model):
|
||||||
|
@ -75,7 +75,7 @@ class TagIndexed(models.Model):
|
||||||
slug = models.SlugField(unique=True)
|
slug = models.SlugField(unique=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
index_together = [["slug", "title"]]
|
index_together = [["slug", "title"]]
|
||||||
|
|
||||||
|
|
||||||
|
@ -84,7 +84,7 @@ class TagUniqueRename(models.Model):
|
||||||
slug2 = models.SlugField(unique=True)
|
slug2 = models.SlugField(unique=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
db_table = "schema_tag"
|
db_table = "schema_tag"
|
||||||
|
|
||||||
|
|
||||||
|
@ -93,7 +93,7 @@ class UniqueTest(models.Model):
|
||||||
slug = models.SlugField(unique=False)
|
slug = models.SlugField(unique=False)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
unique_together = ["year", "slug"]
|
unique_together = ["year", "slug"]
|
||||||
|
|
||||||
|
|
||||||
|
@ -101,4 +101,4 @@ class BookWithLongName(models.Model):
|
||||||
author_foreign_key_with_really_long_field_name = models.ForeignKey(Author)
|
author_foreign_key_with_really_long_field_name = models.ForeignKey(Author)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
app_cache = new_app_cache
|
apps = new_apps
|
||||||
|
|
|
@ -2,7 +2,7 @@ from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.utils.six import StringIO
|
from django.utils.six import StringIO
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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
|
||||||
|
@ -26,7 +26,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_models = app_cache.app_configs['tablespaces'].models.copy()
|
self._old_models = apps.app_configs['tablespaces'].models.copy()
|
||||||
|
|
||||||
for model in Article, Authors, Reviewers, Scientist:
|
for model in Article, Authors, Reviewers, Scientist:
|
||||||
model._meta.managed = True
|
model._meta.managed = True
|
||||||
|
@ -35,9 +35,9 @@ 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
|
||||||
|
|
||||||
app_cache.app_configs['tablespaces'].models = self._old_models
|
apps.app_configs['tablespaces'].models = self._old_models
|
||||||
app_cache.all_models['tablespaces'] = self._old_models
|
apps.all_models['tablespaces'] = self._old_models
|
||||||
app_cache.get_models.cache_clear()
|
apps.get_models.cache_clear()
|
||||||
|
|
||||||
def assertNumContains(self, haystack, needle, count):
|
def assertNumContains(self, haystack, needle, count):
|
||||||
real_count = haystack.count(needle)
|
real_count = haystack.count(needle)
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from django.apps import app_cache
|
from django.apps import apps
|
||||||
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_config = app_cache.get_app_config("test_suite_override")
|
app_config = apps.get_app_config("test_suite_override")
|
||||||
suite = build_suite(app_config)
|
suite = build_suite(app_config)
|
||||||
self.assertEqual(suite.countTestCases(), 1)
|
self.assertEqual(suite.countTestCases(), 1)
|
||||||
|
|
||||||
|
|
|
@ -3,7 +3,7 @@ from __future__ import unicode_literals
|
||||||
import datetime
|
import datetime
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from django.apps.cache import AppCache
|
from django.apps.registry import Apps
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
@ -58,7 +58,7 @@ class GetUniqueCheckTests(unittest.TestCase):
|
||||||
|
|
||||||
Meta = type(str('Meta'), (), {
|
Meta = type(str('Meta'), (), {
|
||||||
'unique_together': unique_together,
|
'unique_together': unique_together,
|
||||||
'app_cache': AppCache()
|
'apps': Apps()
|
||||||
})
|
})
|
||||||
|
|
||||||
checks, _ = M()._get_unique_checks()
|
checks, _ = M()._get_unique_checks()
|
||||||
|
|
Loading…
Reference in New Issue