16

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?

Akash Deshpande
  • 2,583
  • 10
  • 41
  • 82

4 Answers4

43

I would use get_model:

from django.db.models import get_model

mymodel = get_model('some_app', 'SomeModel')
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 2
    Hi. I get an error that says `Cannot import name get_model` in the first line. Did anything change in the latest Django version? – Y2H May 30 '17 at 09:49
  • 4
    @Y2H yes, look here: https://stackoverflow.com/questions/4881607/django-get-model-from-string – Boris Paschenko Jul 26 '17 at 10:41
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'>
>>>
akki
  • 2,021
  • 1
  • 24
  • 35
IJR
  • 1,288
  • 13
  • 14
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
  • 25,178
  • 4
  • 40
  • 42
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
  • 2,762
  • 1
  • 20
  • 49