当前位置:   article > 正文

django动态表技术(根据日期,年月日)方法二

django动态表技术(根据日期,年月日)方法二

方法一:
第一步:在models创建一个类,里边存放数据表中需要的字段,如下

class TemplateModel(models.Model):
    NowTime = models.CharField(max_length=5)
    name = models.CharFiedld(max_length=5)
    class Meta:
        abstract = True  # 基础类设置为抽象模型,不会生成实际数据库表
  • 1
  • 2
  • 3
  • 4
  • 5

第二步:

class NewDynamicModel(object):
    #定义一个字典变量 _instance 用于存储已经创建过的动态模型类
    _instance = dict()

    #一个特殊的方法,重写Python对象实例化时的行为。当调用这个类时,实际上会执行 __new__ 方法而非 __init__ 方法
    #base_cls 在这段代码中是一个基础类(base class),它通常用于作为动态创建的新类的父类
    def __new__(cls, base_cls, date=None):
        # 将date转换
        if not date:
            current_date = datetime.now()
            month = str(current_date.month)
            day = str(current_date.day)
            date = f'{current_date.year}{month}{day}'

        #根据基础类名和格式化后的日期生成新类名,形如BaseModel_To_20220516
        new_cls_name = "%s_To_%s" % (
            base_cls.__name__, '_'.join(map(lambda x: x.capitalize(), date.split('_'))))

        #首先检查 new_cls_name 是否已经存在于 cls._instance 字典中。_instance 是一个字典,用于存储已创建的类实例
        if new_cls_name not in cls._instance:
            #获取 base_cls 类上的 Meta 类属性,并将其赋值给 new_meta_cls
            new_meta_cls = base_cls.Meta
            
            #修改 new_meta_cls.db_table 属性,将其设置为 'table' 加上格式化后的日期字符串
            new_meta_cls.db_table = 'table' + date
            
            #model_cls 是通过 type() 函数动态创建的一个新类,new_cls_name:新创建类的名字
            #元组形式,表示新类继承自 base_cls 类,'__module__': 设置为当前类所在模块的名字
            model_cls = type(new_cls_name, (base_cls,),
                             {'__tablename__': date, 'Meta': new_meta_cls, '__module__': cls.__module__})
            
            #将新创建的类实例添加到 cls._instance 字典中,键为 new_cls_name,这样在后续调用时可以直接通过名字获取到该类
            cls._instance[new_cls_name] = model_cls

        return cls._instance[new_cls_name]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

第三步:我们在views.py中操作,我们获取当前时间作为第二步方法的参数,然后执行django的查询语句,由于我数据表中日期格式是varchar,我将日期转换一下,并进行排序取第一条。

    TodayModel = NewDynamicModel(TemplateModel)
    data = TodayModel.objects.all()
    sorted_data = sorted(data, key=lambda x: datetime.strptime(x.NowTime, '%Y/%m/%d %H:%M:%S'), reverse=True)
    latest_entry = sorted_data[0]
  • 1
  • 2
  • 3
  • 4

第四步:前端页面,接收views.py传来的数据,也就是第三步获得的数据,在前端页面js显示,我将input标签的name和value设置为和数据库字段名

function update_frame3(){
         $.ajax({
            url: '/AAA/update_frame3/',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                response.data.forEach(function(item) {
                    //遍历对象item的所有可枚举属性,每次循环将当前属性名赋值给变量key
                    for (var key in item) {
                         // 检查该属性是否为item对象自身的属性
                        if (item.hasOwnProperty(key)) {
                            // 将值设置到表单中
                            var inputElement = document.getElementById(key);
                            if (inputElement) {
                                inputElement.value = item[key];
                            }
                        }
                    }
                });
            },
        });
     }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/224192
推荐阅读
相关标签
  

闽ICP备14008679号