初学django,许多不懂的地方,还望指教。qq:1685519445
django版本:2.1.0
动态新建表的两个方法如下,可建个文件放到任意地方。引用即可。
# -*- coding: utf-8 -*-
from django.db import models
#name是表名,fields是字段,app_label是你的应用名(如:flow),module是应用下的模型(如:flow.models),options是元类选项
def create_model1(name, fields=None, app_label='', module='', options=None):
class Meta: # 模型类的Meta类
pass
if app_label: # 必须在元类中设置app_label,相关属性可参考https://www.cnblogs.com/lcchuguo/p/4754485.html
setattr(Meta, 'app_label', app_label) # 更新元类的选项
if options is not None:
for key, value in options.items():
setattr(Meta, key, value) # 设置模型的属性
attrs = {'__module__': module, 'Meta': Meta} # 添加字段属性
if fields:
attrs.update(fields) # 创建模型类对象
return type(name, (models.Model,), attrs)
def install(custom_model):
from django.db import connection
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
editor = BaseDatabaseSchemaEditor(connection)
try:
editor.create_model(model=custom_model) #会抛出个异常,不知为啥,但表会创建
except AttributeError as aerror:
print(aerror)
在视图view里面调用:
from flow.model.dynamic_model import install, create_model1
def newflow(request):
fields = {
'type': models.CharField(max_length=100),
'category': models.CharField(max_length=1024),
'title': models.CharField(max_length=10240),
'answer': models.CharField(max_length=200),
'__str__': lambda self: '%s %s %s %s' % (self.type, self.category, self.title, self.answer),
}
options = { 'ordering': ['type', 'category', 'title', 'answer'], 'verbose_name': 'valued customer',}
custom_model = create_model1('testt', fields, options=options, app_label='flow', module='flow.models')
install(custom_model) # 同步到数据库中
我的目录结构:
调用的两个方法我放在了myflow/flow//model/dynamic_model.py内。
访问路由,你会发现表已经创建好了。
网友评论