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?
Asked
Active
Viewed 55 times
0
mohammad
- 1,929
- 1
- 16
- 35
1 Answers
2
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,553
- 2
- 10
- 17