# Create your models here.
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) #用type動態創建類
def install(custom_model):
from django.db import connection
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
"""
fix:
editor = BaseDatabaseSchemaEditor(connection)
try:
editor.create_model(model=custom_model) # 會拋出個異常,不知為啥,但表會創建
except AttributeError as error:
print(error)
在BaseDatabaseSchemaEditor類中有一個__enter__方法,
需要通過with上下文打開以后deferred_sql變量才會在實例化后賦值給editor
這樣就不會有'BaseDatabaseSchemaEditor' object has no attribute 'deferred_sql'
"""
with BaseDatabaseSchemaEditor(connection) as editor:
editor.create_model(model=custom_model)
def CreateNewTab(tabdate):
fields = {
"name": models.CharField(max_length=30),
"job_number": models.IntegerField(unique=True),
"even_shift": models.CharField(max_length=1024),
"administrator_shift": models.CharField(max_length=1024),
"middle_shift": models.CharField(max_length=1024),
"meeting_ops": models.CharField(max_length=1024),
"meeting_ops_manager": models.CharField(max_length=1024),
"checking_station": models.CharField(max_length=1024),
'__str__': lambda self: '%s %s %s %s %s %s %s %s' % (
self.name,
self.job_number,
self.even_shift,
self.administrator_shift,
self.middle_shift,
self.meeting_ops,
self.meeting_ops_manager,
self.checking_station,
), }
options = {'ordering': [
"name",
"job_number",
"even_shift",
"administrator_shift",
"middle_shift",
"meeting_ops",
"meeting_ops_manager",
"checking_station",
], 'verbose_name': 'valued customer', }
custom_model = create_model1(name=tabdate, fields=fields, options=options, app_label='ops_shift_',
module='flow.models')
install(custom_model) # 同步到數據庫中