[Fixed]-How to get a model object using model name string in Django

43๐Ÿ‘

โœ…

I would use get_model:

from django.db.models import get_model

mymodel = get_model('some_app', 'SomeModel')
๐Ÿ‘คChris Pratt

26๐Ÿ‘

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. The 1.7 docs give us the following instead:

$ python manage.py shell
Python 2.7.6 (default, Mar  5 2014, 10:59:47)
>>> from django.apps import apps
>>> User = apps.get_model(app_label='auth', model_name='User')
>>> print User
<class 'django.contrib.auth.models.User'>
>>>
๐Ÿ‘คIJR

4๐Ÿ‘

if you pass in โ€˜app_label.model_nameโ€™ you could use contenttypes e.g.

from django.contrib.contenttypes.models import ContentType

model_type = ContentType.objects.get(app_label=app_label, model=model_name)
objects = model_type.model_class().objects.all()
๐Ÿ‘คJamesO

0๐Ÿ‘

The full answer for Django 1.5 is:

from django.db.models.loading import AppCache

app_cache = AppCache()
model_class = app_cache.get_model(*'myapp.MyModel'.split('.',1))
๐Ÿ‘คjacob

Leave a comment