我有一些表类,我将不断添加属性。我想编写一个函数upToDate(),如果没有列是MySQL默认值,则返回True,如果没有,则返回False。例如,我的表格如下:
class League(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
numTeams = db.Column(db.Integer, nullable=False)
我加载了联盟ID 1,它已经填充了所有值,因此返回True。后来,我更新联盟看起来像这样:
class League(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
numTeams = db.Column(db.Integer, nullable=False)
firstYear = db.Column(db.Integer, nullable=False)
我运行migrate()和update()以将新列添加到数据库。现在当我加载League id 1时,firstYear属性将为0,这是默认值,这意味着它需要更新。
答案 0 :(得分:2)
我在SQLAlchemy文档中找到了inspect()函数,它为我解决了这个问题。
def upToDate(tableObject):
defaults = {"INTEGER" : 0, "VARCHAR(128)" : ""} #could enter more data types here as necessary
mapper = inspect(tableObject.__class__)
for col in mapper.columns:
name = col.name
type = str(col.type)
currentValue = tableObject.__getattribute__(name)
if defaults[type] == currentValue:
return False
return True