0

I was referring this link : Django: Get model from string? . And, I found there is a way to do this by using apps.get_model. But,In my scenario, the model can be from other apps. So, I can't actually name the app_name here. Is there any way to do this ?

Jinto Antony
  • 458
  • 8
  • 26
  • This isn't clear. A model can only be from one app. Why can't you specify the app? – Daniel Roseman Apr 28 '18 at 13:21
  • I can't specify the app name bcoz, the model name is a dynamic, and gets from the url. It can come from any app. – Jinto Antony Apr 28 '18 at 13:48
  • Welcome to stackoverflow.com. Please take some time to read the [help pages](https://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](https://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](https://stackoverflow.com/help/dont-ask). Also please [take the tour](https://stackoverflow.com/tour) and read about [how to ask](https://stackoverflow.com/help/how-to-ask) good questions. Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) – Brown Bear Apr 28 '18 at 14:07

1 Answers1

5

If you don't care which app the model comes from, you can do it the following way:

from django.apps import apps

def get_model_from_any_app(model_name):

    for app_config in apps.get_app_configs():
        try:
            model = app_config.get_model(model_name)
            return model
        except LookupError:
            pass

model = get_model_from_any_app('SomeModelName')

But in Django models in different apps can have the same name, i.e. your project can have model Post in your blog app and model Post in your news app etc.

So this way you can end up with not the model you expect, if they have duplicate names across apps (i.e. you probably should not do it this way, just think why in the world would you want a semi-random model?).

Docs which explain the code: https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.apps.get_app_configs https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.get_model

Bob
  • 5,809
  • 5
  • 36
  • 53