Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a model object using model name string in Django

Desciption:

I have a generic function

def gen(model_name,model_type): 
      objects = model_name.objects.all()
      for object in objects:
          object.model_type = Null      (Or some activity)
          object.save()

How Can I achieve the above ? Is it possible?

like image 844
Akash Deshpande Avatar asked Sep 05 '12 10:09

Akash Deshpande


2 Answers

I would use get_model:

from django.db.models import get_model

mymodel = get_model('some_app', 'SomeModel')
like image 53
Chris Pratt Avatar answered Nov 20 '22 09:11

Chris Pratt


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'>
>>>
like image 27
IJR Avatar answered Nov 20 '22 10:11

IJR