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

别等时光非礼了梦想. 提交于 2019-12-21 03:53:32

问题


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?


回答1:


I would use get_model:

from django.db.models import get_model

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



回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/12279846/how-to-get-a-model-object-using-model-name-string-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!