How to get a model object using model name string in Django
亵渎:
我有一个通用函数
1 2 3 4 5 | def gen(model_name,model_type): objects = model_name.objects.all() for object in objects: object.model_type = Null (Or some activity) object.save() |
我如何才能实现上述目标?有可能吗?
我会用
1 2 3 | from django.db.models import get_model mymodel = get_model('some_app', 'SomeModel') |
自Django 1.7起,为了支持新的应用程序加载系统,不推荐使用
1 2 3 4 5 6 7 | $ 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'> >>> |
如果你输入"app-label.model-name",你可以使用contenttypes,例如
1 2 3 4 | 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() |
Django 1.5的完整答案是:
1 2 3 4 | from django.db.models.loading import AppCache app_cache = AppCache() model_class = app_cache.get_model(*'myapp.MyModel'.split('.',1)) |