django生成动态表名

common.py公共文件
from
django.db import models from common.get_logger import Logger logger = Logger().info class CreateTable(object): # name是表名,fields是字段,app_label是你的应用名(如:flow),module是应用下的模型(如:flow.models),options是元类选项 def create_model(self, name, fields=None, app_label='', module='', options=None): class Meta: # 模型类的Meta类 db_table = name if app_label: # 必须在元类中设置app_label 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) # 创建模型类对象 try: model = type(name, (models.Model,), attrs) return model # 用type动态创建类 except Exception as e: logger.error(e) def install(self, custom_model): from django.db import connection from django.db.backends.base.schema import BaseDatabaseSchemaEditor with BaseDatabaseSchemaEditor(connection) as editor: try: editor.create_model(model=custom_model) logger.info("创建表%s" % custom_model) except Exception as e: logger.info("表已存在,添加数据")

models.py文件

class Module(CreateTable):
    """创建module_%s表"""

    def CreateNewTab(self, table_name):

        fields = {
            "station_id": models.IntegerField(db_index=True, blank=True, null=True),  # 关联station表id
            "serial_id": models.CharField(max_length=255, blank=True, null=True),  # 组件序列号
            "img_name": models.CharField(max_length=255, blank=True, null=True),  # 图像名称
            "grid_lines_by_row": models.CharField(max_length=500, blank=True, null=True),  # 电池片水平分割线的json字符串, 例如:'[9,500,1009,1500,2000,2502,3010]'
            "grid_lines_by_col": models.CharField(max_length=500, blank=True, null=True),  # 电池片垂直分割线的json字符串
            "shift": models.CharField(max_length=255, blank=True, null=True),  # 班次:2010.06.08-白班
            "rows": models.IntegerField(db_index=True, blank=True, null=True),  # 组件电池片的行数
            "cols": models.IntegerField(db_index=True, blank=True, null=True),  # 组件电池片的列数
            "monocrystal": models.BooleanField(default=0),  # 是否为单晶
            "half_plate": models.BooleanField(default=0),  # 是否为半片
            "module_type": models.CharField(max_length=255, blank=True, null=True),  # 5BB, 9BB, 叠瓦
            "is_ng": models.BooleanField(default=0),  # 是否判为ng图片
            "is_ng_ai": models.BooleanField(default=0),  # 是否判为ng图片
            "create_time": models.DateTimeField(auto_now_add=True),  # 创建时间
            '__str__': lambda self: '%s %s %s %s %s %s %s %s %s %s %s %s %s %s' % (
                self.station_id,
                self.serial_id,
                self.img_name,
                self.grid_lines_by_row,
                self.grid_lines_by_col,
                self.shift,
                self.rows,
                self.cols,
                self.monocrystal,
                self.half_plate,
                self.module_type,
                self.is_ng,
                self.is_ng_ai,
                self.create_time,
            ), }
        options = {}
        custom_model = self.create_model(name=table_name, fields=fields, options=options, app_label='pvmi',
                                     module='pvmi.models')
        self.install(custom_model)  # 同步到数据库
        return custom_model

views.py中调用创建并添加数据

def test(request):

    station_id = 1
    table_name = "module_test_%s" % station_id
    module = Module()
    module_table = module.CreateNewTab(table_name=table_name)
    module_table.objects.create(rows=2, is_ng_ai=1)

    return HttpResponse("ok")

 

posted @ 2021-04-22 11:32  Mr沈  阅读(481)  评论(0编辑  收藏  举报