1

In Django I know that there is one and only one model with name foo, but I don't know the app that this model is registered with! How can I get the model with only model_name?

mohammad
  • 2,232
  • 1
  • 18
  • 38

2 Answers2

6

As the answers to Django: Get model from string? show, you need either the app_name string or an AppConfig object to get a model from model_name.

However, you can use apps.get_app_configs() to iterate over AppConfig instances, so something like this is possible:

from django.apps import apps

for app_conf in apps.get_app_configs():
    try:
        foo_model = app_conf.get_model('foo')
        break # stop as soon as it is found
    except LookupError:
        # no such model in this application
        pass

Note that this iterable will include base django apps that are in INSTALLED_APPS like admin, auth, contenttypes, sessions, messages and staticfiles.

shriakhilc
  • 2,922
  • 2
  • 12
  • 17
2
  1. Get all models.
from django.apps import apps
apps.get_models()
  1. Get model by app name and model_name.
from django.apps import apps
apps.get_model(app_label="your_app_label", model_name="your_model_name_in_lower_case")
  1. model can be also get by simply.
from django.apps import apps
apps.get_model('app_label.model_name')

Also, To know the model_name

from your_app.models import your_model
your_model._meta.model_name
Furkan Siddiqui
  • 1,725
  • 12
  • 19