我将一个变量传递给我的视图,这是要查询的模型的名称。
model_name = 'application'
assets = model_name.objects.all()
我得到unicode对象没有objects
属性的错误,这是有意义的,因为我的调试器按预期显示model_name = u'application'
(不是想要的)。
我认为它与* args和** kwargs(我是新手,但我认为我得到)有关,特别是因为我的代码中的其他地方:
role_set = ['primary_tech', 'primary_biz', 'backup_tech', 'backup_biz']
for role in role_set:
records_to_change = Item.objects.filter(**{role:old_owner})
工作正常。我尝试了我能想到的*和**的每个组合,以及为了一致性而将它包装在for model_name in [model_name]
中,并且一切都给了我语法错误。我错过了什么?
Python 2.7,Django 1.5
回溯:
Environment:
Request Method: GET
Request URL: http://localhost:8000/application/all/
Django Version: 1.6.1
Python Version: 2.7.2
Installed Applications:
('suit',
'south',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.redirects',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'rest_framework',
'ldap_sync',
'crispy_forms',
'ownership.apps.Catalog',
'ownership.apps.Assets',
'ownership.apps.Shared',
'ownership.libs.display',
'django_tables2',
'haystack',
'autocomplete_light',
'reversion',
'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'reversion.middleware.RevisionMiddleware',
'ownership.libs.shibboleth.CustomHeaderMiddleware',
'ownership.libs.middleware.LoginRequiredMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/nicholsp/.virtualenvs/ownership/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
90. response = middleware_method(request)
File "/Users/nicholsp/.virtualenvs/ownership/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
40. __import__(name)
File "/Users/nicholsp/code/ownership/ownership/urls.py" in <module>
27. url(r'^', include('ownership.apps.Assets.urls'), name='home'),
File "/Users/nicholsp/.virtualenvs/ownership/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include
26. urlconf_module = import_module(urlconf_module)
File "/Users/nicholsp/.virtualenvs/ownership/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
40. __import__(name)
File "/Users/nicholsp/code/ownership/ownership/apps/Assets/urls.py" in <module>
3. import views
Exception Type: SyntaxError at /application/all/
Exception Value: invalid syntax (views.py, line 132)
答案 0 :(得分:1)
from django.db.models import get_model
class MyModel(models.Model):
...
model_class = get_model('myapp', 'mymodel')
print model_class.__name__
'MyModel'
model_class.objects.all()
[<MyModel: 1>, <MyModel: 2>, <MyModel: 3>, ... ]