ORM动态创建模型类Django
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
网络游戏排行榜2014前十名
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 = _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:
ate_model(mydata)
return mydata
# 查询,表不存在则创建
entry_data = getmodels("Entrydata", str('2020')).lude(state="9").filter(
target__adminapp_id=app,
target__cycletype=cycletype,
target__work=work,
datadate=now)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。