Python django.apps.apps.get_models() Examples

The following are 30 code examples of django.apps.apps.get_models(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.apps.apps , or try the search function .
Example #1
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 [] 
Example #2
Source File: utils.py    From django-unused-media with MIT License 6 votes vote down vote up
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 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: signals.py    From django-htk with MIT License 6 votes vote down vote up
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() 
Example #5
Source File: kml.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: kml.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #7
Source File: panels.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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()}) 
Example #8
Source File: model_checks.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #9
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #10
Source File: kml.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #11
Source File: related.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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 [] 
Example #12
Source File: fix_proxy_permissions.py    From django-admin-view-permission with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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)) 
Example #13
Source File: merge.py    From django-uniauth with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_generic_fields():
    """
    Return a list of all GenericForeignKeys in all models.
    """
    generic_fields = []
    for model in apps.get_models():
        for field_name, field in model.__dict__.items():
            if isinstance(field, GenericForeignKey):
                generic_fields.append(field)
    return generic_fields 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_models_not_loaded(self):
        """
        apps.get_models() raises an exception if apps.models_ready isn't True.
        """
        apps.models_ready = False
        try:
            # The cache must be cleared to trigger the exception.
            apps.get_models.cache_clear()
            with self.assertRaisesMessage(AppRegistryNotReady, "Models aren't loaded yet."):
                apps.get_models()
        finally:
            apps.models_ready = True 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_models_only_returns_installed_models(self):
        self.assertNotIn(
            "NotInstalledModel",
            [m.__name__ for m in apps.get_models()]) 
Example #16
Source File: utils.py    From dj-spam with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def spammables():
    # Lists all models that are marked flaggable
    flaggables = []
    for model in apps.get_models():
        try:
            model._meta.get_field_by_name('spam_flag')
        except FieldDoesNotExist:
            continue
        flaggables.append(model)
    return flaggables 
Example #17
Source File: test_runners.py    From modoboa-amavis with MIT License 5 votes vote down vote up
def setup_test_environment(self, *args, **kwargs):
        """Mark modoboa_amavis models as managed during testing
        During database setup migrations are only run for managed models"""
        for m in apps.get_models():
            if m._meta.app_label == "modoboa_amavis":
                self.unmanaged_models.append(m)
                m._meta.managed = True
        super(UnManagedModelTestRunner, self).setup_test_environment(
            *args, **kwargs) 
Example #18
Source File: deleteorphanedmedia.py    From django-cloudinary-storage with MIT License 5 votes vote down vote up
def models(self):
        """
        Gets all registered models.
        """
        return apps.get_models() 
Example #19
Source File: admin.py    From django-collaborative with MIT License 5 votes vote down vote up
def register(self):
        try:
            create_models()
        except Exception:
            pass
        for Model in apps.get_models():
            if not self.should_register_admin(Model):
                continue

            ModelAdmin = self.create_admin(Model)
            self.attempt_register(Model, ModelAdmin) 
Example #20
Source File: createinitialfieldhistory.py    From django-field-history with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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.') 
Example #21
Source File: object_permission.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #22
Source File: tasks.py    From django-htk with MIT License 5 votes vote down vote up
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) 
Example #23
Source File: utils.py    From django-htk with MIT License 5 votes vote down vote up
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)) 
Example #24
Source File: views.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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) 
Example #25
Source File: checks.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: checks.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #27
Source File: signal_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #28
Source File: models.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_generic_relations(cls):
        for model in apps.get_models():
            if class_is_indexed(model):
                TextIDGenericRelation(cls).contribute_to_class(model,
                                                               'index_entries') 
Example #29
Source File: utils.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #30
Source File: utils.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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