Python源码示例:django.apps.apps.get_models()
示例1
def _check_referencing_to_swapped_model(self):
if (self.rel.to not in apps.get_models() and
not isinstance(self.rel.to, six.string_types) and
self.rel.to._meta.swapped):
model = "%s.%s" % (
self.rel.to._meta.app_label,
self.rel.to._meta.object_name
)
return [
checks.Error(
("Field defines a relation with the model '%s', "
"which has been swapped out.") % model,
hint="Update the relation to point at 'settings.%s'." % self.rel.to._meta.swappable,
obj=self,
id='fields.E301',
)
]
return []
示例2
def swappable_setting(self):
"""
Gets the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
"""
if self.swappable:
# Work out string form of "to"
if isinstance(self.rel.to, six.string_types):
to_string = self.rel.to
else:
to_string = "%s.%s" % (
self.rel.to._meta.app_label,
self.rel.to._meta.object_name,
)
# See if anything swapped/swappable matches
for model in apps.get_models(include_swapped=True):
if model._meta.swapped:
if model._meta.swapped == to_string:
return model._meta.swappable
if ("%s.%s" % (model._meta.app_label, model._meta.object_name)) == to_string and model._meta.swappable:
return model._meta.swappable
return None
示例3
def _build_kml_sources(self, sources):
"""
Goes through the given sources and returns a 3-tuple of
the application label, module name, and field name of every
GeometryField encountered in the sources.
If no sources are provided, then all models.
"""
kml_sources = []
if sources is None:
sources = apps.get_models()
for source in sources:
if isinstance(source, models.base.ModelBase):
for field in source._meta.fields:
if isinstance(field, GeometryField):
kml_sources.append((source._meta.app_label,
source._meta.model_name,
field.name))
elif isinstance(source, (list, tuple)):
if len(source) != 3:
raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).')
kml_sources.append(source)
else:
raise TypeError('KML Sources must be a model or a 3-tuple.')
return kml_sources
示例4
def check_all_models(app_configs=None, **kwargs):
errors = []
for model in apps.get_models():
if app_configs is None or model._meta.app_config in app_configs:
if not inspect.ismethod(model.check):
errors.append(
Error(
"The '%s.check()' class method is "
"currently overridden by %r." % (
model.__name__, model.check),
hint=None,
obj=model,
id='models.E020'
)
)
else:
errors.extend(model.check(**kwargs))
return errors
示例5
def collect_invalidations(self):
models = apps.get_models()
data = defaultdict(list)
cache = cachalot_caches.get_cache()
for db_alias in settings.DATABASES:
get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
model_cache_keys = {
get_table_cache_key(db_alias, model._meta.db_table): model
for model in models}
for cache_key, timestamp in cache.get_many(
model_cache_keys.keys()).items():
invalidation = datetime.fromtimestamp(timestamp)
model = model_cache_keys[cache_key]
data[db_alias].append(
(model._meta.app_label, model.__name__, invalidation))
if self.last_invalidation is None \
or invalidation > self.last_invalidation:
self.last_invalidation = invalidation
data[db_alias].sort(key=lambda row: row[2], reverse=True)
self.record_stats({'invalidations_per_db': data.items()})
示例6
def _build_kml_sources(self, sources):
"""
Go through the given sources and return a 3-tuple of the application
label, module name, and field name of every GeometryField encountered
in the sources.
If no sources are provided, then all models.
"""
kml_sources = []
if sources is None:
sources = apps.get_models()
for source in sources:
if isinstance(source, models.base.ModelBase):
for field in source._meta.fields:
if isinstance(field, GeometryField):
kml_sources.append((source._meta.app_label,
source._meta.model_name,
field.name))
elif isinstance(source, (list, tuple)):
if len(source) != 3:
raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).')
kml_sources.append(source)
else:
raise TypeError('KML Sources must be a model or a 3-tuple.')
return kml_sources
示例7
def _build_kml_sources(self, sources):
"""
Goes through the given sources and returns a 3-tuple of
the application label, module name, and field name of every
GeometryField encountered in the sources.
If no sources are provided, then all models.
"""
kml_sources = []
if sources is None:
sources = apps.get_models()
for source in sources:
if isinstance(source, models.base.ModelBase):
for field in source._meta.fields:
if isinstance(field, GeometryField):
kml_sources.append((source._meta.app_label,
source._meta.model_name,
field.name))
elif isinstance(source, (list, tuple)):
if len(source) != 3:
raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).')
kml_sources.append(source)
else:
raise TypeError('KML Sources must be a model or a 3-tuple.')
return kml_sources
示例8
def priority_connect(self, receiver, sender=None, children=True):
if sender and children:
if sender._meta.abstract:
for child in apps.get_models():
if issubclass(child, sender):
priority_connect(self, receiver, child, children=False)
return
lookup_key = (_make_id(receiver), _make_id(sender))
with self.lock:
self._clear_dead_receivers()
for r_key, _ in self.receivers:
if r_key == lookup_key:
break
else:
# Adding priority receiver to beginning of the list
self.receivers.insert(0, (lookup_key, receiver))
self.sender_receivers_cache.clear()
示例9
def test_dynamic_load(self):
"""
Makes a new model at runtime and ensures it goes into the right place.
"""
old_models = list(apps.get_app_config("apps").get_models())
# Construct a new model in a new app registry
body = {}
new_apps = Apps(["apps"])
meta_contents = {
'app_label': "apps",
'apps': new_apps,
}
meta = type("Meta", (), 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(list(apps.get_app_config("apps").get_models()), old_models)
with self.assertRaises(LookupError):
apps.get_model("apps", "SouthPonies")
self.assertEqual(new_apps.get_model("apps", "SouthPonies"), temp_model)
示例10
def get_file_fields():
"""
Get all fields which are inherited from FileField
"""
# get models
all_models = apps.get_models()
# get fields
fields = []
for model in all_models:
for field in model._meta.get_fields():
if isinstance(field, models.FileField):
fields.append(field)
return fields
示例11
def _check_relation_model_exists(self):
rel_is_missing = self.rel.to not in apps.get_models()
rel_is_string = isinstance(self.rel.to, six.string_types)
model_name = self.rel.to if rel_is_string else self.rel.to._meta.object_name
if rel_is_missing and (rel_is_string or not self.rel.to._meta.swapped):
return [
checks.Error(
("Field defines a relation with model '%s', which "
"is either not installed, or is abstract.") % model_name,
hint=None,
obj=self,
id='fields.E300',
)
]
return []
示例12
def check_generic_foreign_keys(**kwargs):
from .fields import GenericForeignKey
errors = []
fields = (obj
for cls in apps.get_models()
for obj in six.itervalues(vars(cls))
if isinstance(obj, GenericForeignKey))
for field in fields:
errors.extend(field.check())
return errors
示例13
def handle(self, *args, **options):
# We need to execute the post migration callback manually in order
# to append the view permission on the proxy model. Then the following
# script will create the appropriate content type and move the
# permissions under this. If we don't call the callback the script
# will create only the basic permissions (add, change, delete)
update_permissions(
apps.get_app_config('admin_view_permission'),
apps.get_app_config('admin_view_permission'),
verbosity=1,
interactive=True,
using='default',
)
for model in apps.get_models():
opts = model._meta
ctype, created = ContentType.objects.get_or_create(
app_label=opts.app_label,
model=opts.object_name.lower(),
)
for codename, name in get_all_permissions(opts, ctype):
perm, created = Permission.objects.get_or_create(
codename=codename,
content_type=ctype,
defaults={'name': name},
)
if created:
self.delete_parent_perms(perm)
self.stdout.write('Adding permission {}\n'.format(perm))
示例14
def __init__(self):
models = apps.get_models()
self.model_classes = dict(map(lambda x: (x._meta.db_table, x), models))
self.models = dict(map(lambda x: (self.model_key(x), self.serialize_model(x)), models))
for model in models:
for related_model in self.get_related_models(model):
if self.model_key(related_model) in self.models:
continue
self.models[self.model_key(related_model)] = self.serialize_model(related_model)
self.media_storage = get_storage_class(settings.JET_MEDIA_FILE_STORAGE)()
示例15
def get_descendant_models(cls):
return [model for model in apps.get_models()
if issubclass(model, AbstractBaseRule)]
示例16
def generate_view_permissions():
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.apps import apps
for model in apps.get_models():
Permission.objects.get_or_create(
codename='view_{}'.format(model._meta.model_name),
name='Can view {}'.format(model._meta.verbose_name),
content_type=ContentType.objects.get_for_model(model),
)
示例17
def populate(self):
if self._registry:
return
models = apps.get_models()
for m in models:
self._registry[m._meta.model_name.lower()] = m
示例18
def get_form(self):
config_models = [
model for model in apps.get_models() if issubclass(model, ByroConfiguration)
]
data = self.request.POST if self.request.method == "POST" else None
return [
forms.modelform_factory(
model, fields="__all__", exclude=("registration_form",)
)(prefix=model.__name__, instance=model.get_solo(), data=data)
for model in config_models
]
示例19
def read_models(self) -> None:
self.models = apps.get_models(include_auto_created=True, include_swapped=True)
for model in self.models:
if self.DEPRECATED_CLASS_NAMES.match(model.__name__):
continue
self.table_by_model[model] = model._meta.db_table
self.model_by_table[self.table_by_model[model]] = model
return
示例20
def get_indexed_models():
return [
model for model in apps.get_models()
if issubclass(model, Indexed) and not model._meta.abstract
]
示例21
def get_descendant_models(model):
"""
Returns all descendants of a model, including the model itself.
"""
descendant_models = {other_model for other_model in apps.get_models()
if issubclass(other_model, model)}
descendant_models.add(model)
return descendant_models
示例22
def get_boosts():
boosts = set()
for model in apps.get_models():
if issubclass(model, Indexed):
for search_field in get_search_fields(model.get_search_fields()):
boost = search_field.boost
if boost is not None:
boosts.add(boost)
return boosts
示例23
def add_generic_relations(cls):
for model in apps.get_models():
if class_is_indexed(model):
TextIDGenericRelation(cls).contribute_to_class(model,
'index_entries')
示例24
def register_signal_handlers():
# Get list of models that are page types
Page = apps.get_model('wagtailcore', 'Page')
indexed_models = [model for model in apps.get_models() if issubclass(model, Page)]
# Loop through list and register signal handlers for each one
for model in indexed_models:
page_published.connect(page_published_signal_handler, sender=model)
page_unpublished.connect(page_unpublished_signal_handler, sender=model)
示例25
def check_generic_foreign_keys(**kwargs):
from .fields import GenericForeignKey
errors = []
fields = (obj
for cls in apps.get_models()
for obj in six.itervalues(vars(cls))
if isinstance(obj, GenericForeignKey))
for field in fields:
errors.extend(field.check())
return errors
示例26
def get_context_data(self, **kwargs):
m_list = [m._meta for m in apps.get_models()]
kwargs.update({'models': m_list})
return super(ModelIndexView, self).get_context_data(**kwargs)
示例27
def get_model_by_name(clazz):
global _model_name_cache
if _model_name_cache is None:
_model_name_cache = {format_model_name(model): model for model in apps.get_models()}
model = _model_name_cache.get(clazz)
if model:
return model
raise Exception("Model {} not found".format(clazz))
示例28
def verify_materialized_properties():
for cls, mps in registered_mps.items():
if cls._meta.abstract:
for child in (x for x in apps.get_models() if issubclass(x, cls) and not x._meta.abstract):
verify_cls(child, mps)
else:
verify_cls(cls, mps)
示例29
def get_models_with_object_permissions():
"""
Return a list of all models that inherit from `ObjectPermissionMixin`
"""
models = []
for model in apps.get_models():
if issubclass(model, ObjectPermissionMixin):
models.append(model)
return models
示例30
def handle(self, *args, **options):
models = []
for model in apps.get_models():
for member in inspect.getmembers(model):
if isinstance(member[1], FieldHistoryTracker):
models.append((model, member[1].fields))
break
if models:
self.stdout.write('Creating initial field history for {} models\n'.format(len(models)))
for model_fields in models:
model = model_fields[0]
fields = model_fields[1]
for obj in model._default_manager.all():
for field in list(fields):
content_type = ContentType.objects.get_for_model(obj)
if not FieldHistory.objects.filter(
object_id=obj.pk,
content_type=content_type,
field_name=field).exists():
data = serializers.serialize(get_serializer_name(),
[obj],
fields=[field])
FieldHistory.objects.create(
object=obj,
field_name=field,
serialized_data=data,
)
else:
self.stdout.write('There are no models to create field history for.')