def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
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}
# Add in any fields that were provided
if fields:
attrs.update(fields)
# Create the class, which automatically triggers ModelBase processing
model = type(name, (models.Model,), attrs)
# Create an Admin class if admin options were provided
if admin_opts is not None:
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts:
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
from dynamicmodel.models import DynamicModel, DynamicSchema, DynamicForm
def csv_to_model(path_to_csv):
with open(path_to_csv, "rb") as f:
reader = csv.reader(f)
col_names = next(reader)
schema = DynamicSchema.get_for_model(MyModel)
for name in col_names:
schema.add_field(name=name, type='CharField')
return schema
你想要的是创建
Dynamic Models
。关于这一点,wiki上有一篇非常详细的文章:Django Dynamic Models它逐步解释了如何实现动态模型。这篇文章的一个快速示例:
实现一个能够按需构建模型的功能:
现在,您可以解析CSV文件并确定字段,然后创建模型:
^{pr2}$当然,你可以做更复杂的模型。阅读wiki以获得更彻底的解释。
存在这样一个django包:django-dynamic-model,它声称在django上添加动态模型创建(我无法确认是否有效):
相关问题 更多 >
编程相关推荐