【问题标题】:Python SQLAlchemy ORM: Update row with instance of classPython SQLAlchemy ORM:使用类实例更新行
【发布时间】:2020-06-18 02:40:24
【问题描述】:

我正在尝试根据类的实例创建一个用于更新数据库中行的函数。

基本上我想做这样的事情:

def update_table(self, result):
    session = self.Session()

    session.query(result.__class__).filter_by(id=result.id).update(result)

    session.commit()
    session.close_all()


user = db.Model.User(
  id = 1,
  name = "foo"
)

# Store user to db
db.save(user)

updated_user = db.Model.User(
    id = 1,
    user = "bar"
)

# Update the users name with id=1
update_table(updated_user)

问题是会话查询导致

TypeError: 'User' 对象不可迭代

但在我看来,这最终应该是更新后的用户,名称为“bar”。

有没有办法使用 SQLAlchemy ORM 创建这样的函数?

【问题讨论】:

标签: python mysql flask sqlalchemy pymysql


【解决方案1】:

您不需要额外的更新程序...

user = db.Model.User(
  id = 1,
  name = "foo"
)

# Store user to db
db.save(user)

new_user = session.query(User).filter(User.id==1).first()
new_user.name = "bar"
session.commit()

【讨论】:

  • 与我的想法不太一样,这个想法是一种更通用的方法。但可能是一个有用的思路。
【解决方案2】:

我最终得到了这个解决方案:

# Update single entry
def update_table_by_id(self, entry):
    # Open connection to database
    session = self.Session()

    # Fetch entry from database
    db_result = session.query(entry.__class__).filter_by(id=entry.id)

    # Convert Models to dicts
    entry_dict = entry.as_dict()
    db_result_dict = db_result.first().as_dict()

    # Update database result with passed in entry. Skip of None
    for value in entry_dict:
        if entry_dict[value] is not None:
            db_result_dict[value] = entry_dict[value]

    # Update db and close connections
    db_result.update(db_result_dict)
    session.commit()
    session.close_all()

它允许我发送任意模型,它们的处理方式都是一样的。

欢迎提出建议和改进!

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 2014-06-02
    • 1970-01-01
    • 2022-08-24
    相关资源
    最近更新 更多