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)

 

posted @   困了就睡觉觉  Views(349)  Comments(0Edit  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示