django1.6, 通过字符串和get_app、get_model获得对应的object
只需要两行代码:from django.db.models import get_model
get_model('auth', 'User')
下面是详细的过程展示:
>>> from django.db.models import get_app, get_models, get_model
# auth是django自带的app, get_app需要一个参数:app_name
>>> get_app('auth')
<module 'django.contrib.auth.models' from '/opt/project/easyui/lib/python2.7/site-packages/django/contrib/auth/models.pyc'>
>>> app = get_app('auth')
# 获得一个app的所有model
>>> get_models(app)
[<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.auth.models.Group'>, <class 'django.contrib.auth.models.User'>
# 下面两种方式,得到的User是一样的, get_model需要两个参数,app_name和model_name
>>> get_model('auth', 'User')
<class 'django.contrib.auth.models.User'>
>>> from django.contrib.auth.models import User
>>> User
<class 'django.contrib.auth.models.User'>
>>> get_model('auth', 'User') == User
True
>>> u = get_model('auth', 'User')
>>> u.objects.all()[0]
<User: root>
django1.7, 可以使用上面的方法,也可以用新增加的django.apps来获取
>>> from django.apps import apps
>>> apps.get_app_config('auth')
<AuthConfig: auth>
# 注意得到的结果是迭代器(iterator)
>>> auth = apps.get_app_config('auth')
>>> auth.get_models()
<generator object get_models at 0x31422d0>
>>> for i in auth.get_models():
... print i
...
<class 'django.contrib.auth.models.Permission'>
<class 'django.contrib.auth.models.Group'>
<class 'django.contrib.auth.models.User'>
>>> auth.get_model('User')
<class 'django.contrib.auth.models.User'>
>>> User = auth.get_model('User')
>>> User.objects.all()[0]
<User: root>
注意,django1.7之前的版本没有django.apps
>>> import django
>>> django.get_version()
'1.6.5'
>>> from django.apps import apps
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named apps