Django: Get model from string?

mpen picture mpen · Feb 3, 2011 · Viewed 77.8k times · Source

In Django, you can specify relationships like:

author = ForeignKey('Person')

And then internally it has to convert the string "Person" into the model Person.

Where's the function that does this? I want to use it, but I can't find it.

Answer

mpen picture mpen · Feb 3, 2011

As of Django 3.0, it's AppConfig.get_model(model_name, require_ready=True)

As of Django 1.9 the method is django.apps.AppConfig.get_model(model_name).
-- danihp

As of Django 1.7 the django.db.models.loading is deprecated (to be removed in 1.9) in favor of the the new application loading system.
-- Scott Woodall


Found it. It's defined here:

from django.db.models.loading import get_model

Defined as:

def get_model(self, app_label, model_name, seed_cache=True):