ORM动态创建模型类 | Django


作用:动态创建模型类,对应生成数据库表,比如每年的日志量都非常大,或者其他表数据量特别大,需要每年分表存

参考链接

# models.py
def get_entrydata_model(prefix):
    table_name = 't_entrydata_%s' % str(prefix)

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

    class Entrydata(models.Model):
        __metaclass__ = EntrydataMetaclass
        target = models.ForeignKey(Target)
        datadate = models.DateTimeField("开始时间", blank=True, null=True)
        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 Entrydata
# 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
# 查询,表不存在则创建
entry_data = getmodels("Entrydata", str('2020')).objects.exclude(state="9").filter(
                target__adminapp_id=app,
                target__cycletype=cycletype,
                target__work=work,
                datadate=now)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM