如何在Django中使用模型名称字符串获取模型对象

时间:2012-09-05 10:52:40

标签: django django-views

应将描述:

我有一个通用功能

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

我如何实现上述目标?有可能吗?

4 个答案:

答案 0 :(得分:37)

我会使用get_model

from django.db.models import get_model

mymodel = get_model('some_app', 'SomeModel')

答案 1 :(得分:21)

从Django 1.7开始,django.db.models.loading is deprecated(将在1.9中删除)支持新的应用程序加载系统。以下是1.7 docs give us

$ 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'>
>>>

答案 2 :(得分:4)

如果您传入“app_label.model_name”,则可以使用contenttypes,例如

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

答案 3 :(得分:0)

Django 1.5的完整答案是:

from django.db.models.loading import AppCache

app_cache = AppCache()
model_class = app_cache.get_model(*'myapp.MyModel'.split('.',1))