ORM动态创建表

models.py:

def get_meterdata_model(prefix):
    table_name = 't_meterdata_%s' % str(prefix)

    class MeterdataMetaclass(models.base.ModelBase):
        def __new__(cls, name, bases, attrs):
            name += '_' + prefix  # 这是Model的name.
            return models.base.ModelBase.__new__(cls, name, bases, attrs)

    class Meterdata(models.Model):
        __metaclass__ = MeterdataMetaclass
        target = models.ForeignKey(Target,db_index = True)
        datadate = models.DateTimeField("开始时间", blank=True, null=True)
        zerodata = models.CharField("零点走字", null=True, max_length=20)
        twentyfourdata = models.CharField("二十四点走字", null=True, max_length=20)
        metervalue = models.CharField("电表数值", null=True, max_length=20)
        todayvalue = models.DecimalField("当前值", null=True, max_digits=22, decimal_places=7)
        judgevalue = models.DecimalField("调整值", null=True, max_digits=22, decimal_places=7, default=0)
        curvalue = models.DecimalField("最终值", null=True, max_digits=22, decimal_places=7)
        curvaluedate = models.DateTimeField("当前值", null=True)
        curvaluetext = models.CharField("当前值", null=True, max_length=20)
        cumulativemonth = models.DecimalField("月累计值", null=True, max_digits=22, decimal_places=7)
        cumulativequarter = models.DecimalField("季累计值", null=True, max_digits=22, decimal_places=7)
        cumulativehalfyear = models.DecimalField("半年累计值", null=True, max_digits=22, decimal_places=7)
        cumulativeyear = models.DecimalField("年累计值", null=True, max_digits=22, decimal_places=7)
        state = models.CharField("状态", blank=True, null=True, max_length=20)
        releasestate = models.CharField('发布状态', blank=True, default=0, max_length=10)

        @staticmethod
        def is_exists():
            return table_name in connection.introspection.table_names()

        class Meta:
            db_table = table_name

    return Meterdata

views.py:

def getmodels(modelname, year):
    try:
        from django.apps import apps

        mydata = apps.get_model('__main__', modelname + '_' + year)
    except LookupError:if modelname == "entrydata":
            mydata = get_entrydata_model(year)

  if not mydata.is_exists(): with connection.schema_editor() as schema_editor: schema_editor.create_model(mydata) return mydata

sql server数据库中的表:

使用:

# 查询
entry_data = getmodels("Entrydata",str('2020')).objects.exclude(state="9").filter(
          target__adminapp_id=app,target__cycletype=cycletype,target__work=work,datadate=now)

# 保存,表不存在则先创建表,再保存数据
# result = {'curvalue':100, 'cumulativemonth':200, 'cumulativequarter':300, 'cumulativeyear':400} 
getmodels("Entrydata", str('2020')).objects.exclude(state="9").filter(id=500).update(**result)
原文地址:https://www.cnblogs.com/zhangguosheng1121/p/14597087.html