作用:動態創建模型類,對應生成數據庫表,比如每年的日志量都非常大,或者其他表數據量特別大,需要每年分表存。
# 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)