我正在尝试动态构造一些类,这些类是django的models.Model的子类。我的代码如下所示:
MyModel = type('MyModel', (models.Model,), {
'field': models.BooleanField()
})
当Django尝试加载它时,它会给出以下异常:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 88, in inner_run
self.validate(display_num_errors=True)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/lib/python2.7/site-packages/django/core/management/validation.py", line 36, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/usr/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/user/project/app/models.py", line 221, in <module>
'field': models.BooleanField()
File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 38, in __new__
module = attrs.pop('__module__')
KeyError: '__module__'
使用type()
构建的类似乎没有获得__module__
成员,该成员是使用class
定义的类。这是怎么回事?
答案 0 :(得分:13)
对于您的需求,metaclasses可能是最低级type()
的最佳选择吗?
但在大多数情况下,您可以使用__name__
作为__module__
的值,例如
MyModel = type('MyModel', (models.Model,), {
'field': models.BooleanField(),
'__module__': __name__,
})
Django使用__module__
值来确定哪个django应用程序拥有此模型,因此my_app1/models.py
中的模型将包含my_app1.models
,而django知道该文件模块中的模型属于{{1应用程序。