【问题标题】:updating table attributes using kwargs Flask-SQLAlchemy使用 kwargs Flask-SQLAlchemy 更新表属性
【发布时间】:2018-12-09 19:02:18
【问题描述】:

我正在使用 Flask-SQLAlchemy。我有一张有几个属性的表。我有一本字典,其中有 key='attribute-name'value=the_new_value

我想使用字典更新现有的行/条目。有没有办法使用**kwargs 更新条目,而不是手动更新它们?

我在 SQLAlchemy 中发现了两个对 set_attribute 方法的引用:herehere,但是它们都解决了比我所要求的更具体的问题。

我已经尝试过set_attribute,但它对我不起作用。我没有收到任何错误消息,但数据库属性没有改变。我想知道:

1) 在 Flask-SQLAlchemy 中访问/导入 set_attribute 的正确方法是什么?

2) 可以将密钥存储为set_attribute中的**kwargs 的字符串吗?

3) 如果 1) 或 2) 都不是我的问题,那是什么?

至于代码,这就是它的样子,首先是模型:

class Files(UserMixin, db.Model):
    id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    filename_main = db.Column(db.String(264))
    filename_side1 = db.Column(db.String(264))
    filename_side2 = db.Column(db.String(264))

    def update(self, **kwargs):
       for key, value in kwargs.items():
               set_attribute(self, key, value)

在视图中,我想做这样的事情:

files = Files.query.filter_by(id=id).first()
filenames = {'filename_main': 'main.ext', 
             'filename_side1': 'side1.ext', 
             'filename_side2': 'side2.ext'}
files.update(**filenames)

【问题讨论】:

    标签: flask flask-sqlalchemy keyword-argument


    【解决方案1】:

    试试这个

    def update(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
    

    【讨论】:

    • 这是迄今为止更好的解决方案
    【解决方案2】:

    我会这样实现更新方法:

    @staticmethod  
    def update(new_data, id):
                # note that this method is static and
                # you have to pass id of the object you want to update
        keys = new_data.keys() # new_data in your case is filenames
        files = Files.query.filter_by(id=id).first() # files is the record 
                                                     # you want to update
        for key in keys:
            exec("files.{0} = new_data['{0}']".format(key))
        db.session.commit()
    

    这解决了你的问题。

    【讨论】:

    • 看起来不错。今天晚些时候我会试一试。以前从未使用过 exec。
    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 2016-12-03
    • 2020-10-03
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多