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?

4 Answers 4

43

I would use get_model:

from django.db.models import get_model

mymodel = get_model('some_app', 'SomeModel')
Sign up to request clarification or add additional context in comments.

2 Comments

Hi. I get an error that says Cannot import name get_model in the first line. Did anything change in the latest Django version?
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'>
>>>

Comments

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()

Comments

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.