我的目的是动态生成 Django 模型。
我使用以下代码来创建模型。
def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
class Meta:
# Using type('Meta', ...) gives a dictproxy error during model creation
pass
if app_label:
# app_label must be set using the Meta inner class
setattr(Meta, 'app_label', app_label)
# Update Meta with any options that were provided
if options is not None:
for key, value in options.iteritems():
setattr(Meta, key, value)
# Set up a dictionary to simulate declarations within a class
attrs = {'__module__': module, 'Meta': Meta}
# …Run Code Online (Sandbox Code Playgroud)