因业务需要从不同时期的sqlite数据库中取数据,不同时期的数据库字段是不同的,但是以往用sqlalchemy管理数据库时的model是写死的,就会导致有些字段错误而报错,这时我们就要根据版本动态生成model
众所周知python里的 type() 函数是可以查看一个实例的class类型,但其实 type() 也可以用来创建一个class类,我们可以利用这一点动态创建model,下面放出例子
#model.py
from sqlalchemy import Column, String, Integer,DateTime
from sqlalchemy.ext.declarative import declarative_base
# 创建对象的基类:
Base = declarative_base()
def test(version):
def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
if version == "1.0":
field_dict = {
"__tablename__" : 'student',
"id":Column(Integer, primary_key=True, autoincrement=True),
"name":Column(String(25)),
"to_dict":to_dict
}
elif version == "2.0":
field_dict = {
"__tablename__" : 'student',
"id":Column(Integer, primary_key=True, autoincrement=True),
"name":Column(String(25)),
"class":Column(String(25)),
"gender":Column(String(25)),
"to_dict":to_dict
}
return type("Student",(Base,),field_dict)
#view.py
from model import test
from sqlalchemy.orm import sessionmaker
import pymysql
pymysql.install_as_MySQLdb()
# 初始化数据库连接:
sengine = create_engine('mysql+pymysql://账号:密码@地址:3306/数据库名?charset=utf8')
# 创建Session类型:
s_db = sessionmaker(bind=sengine)
def testDynamicGetModel():
dynamicStudentClass = test('2.0')
db = s_db()
result = db.query(dynamicStudentClass).filter_by(class='6班').first()
db.close()
student_dict = result.to_dict()