作用:动态创建模型类,对应生成数据库表,比如每年的日志量都非常大,或者其他表数据量特别大,需要每年分表存。
# 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)