SQLAlchemy如何检查加载的对象属性是否等于列默认值

问题描述 投票:0回答:1

我有一些表类,我将不断添加属性。我想编写一个函数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,这是默认值,这意味着它需要更新。

python mysql sqlalchemy flask-sqlalchemy
1个回答
2
投票

我在SQLAlchemy文档中找到了inspect()函数,它为我解决了这个问题。

Documentation

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
© www.soinside.com 2019 - 2024. All rights reserved.