【问题标题】:Python's function update() not recognizedPython函数更新()无法识别
【发布时间】:2018-12-11 06:24:47
【问题描述】:
def updateTheme(self, id, new_theme):
    theme = Theme.query.filter_by(id = id).first()
    theme.update(new_theme)
    db.session.commit()

错误:“主题”对象没有属性“更新”
它应该是这样工作的:

theme = Theme(name = "osman")
new_theme = Theme(name = "miras")
theme.update(new_theme)
print(theme) # osman have to be changed to miras

即使我可以这样做:

theme.name = "miras"

当我必须使用多个参数时,例如姓名、姓氏、电话。此外,updateTheme 并不总是提供所有参数(姓名、姓氏、电话),它应该只更新提供的参数。例如:

person = {name: "john", surname: "smith", phone: 12345, country: "USA"}
update_person = {country: "Portugal"}
person.update(update_person) # should change only country

【问题讨论】:

  • 分享完整代码。主题是什么?

标签: python function object methods


【解决方案1】:

如果您想更新一两个字段,您可以使用:

theme = Theme(name = "osman")
new_theme = Theme(name = "miras")
theme.name=new_theme.name
db.session.commit()
print(theme) # osman will change to miras

如果要更新更多字段:

dict_to_update = {'name': new_theme.name}
updated_theme = Theme.query.filter_by(name="miras").update(dict_to_update)
db.session.commit()
print(theme) # osman will change to miras

【讨论】:

  • 仍然错误Theme' object has no attribute 'update'
  • 我知道它是这样工作的。但是想象一下,我有参数(姓名、姓氏、国家/地区、电话……)并且 graphql 尝试仅更新国家/地区和电话,并且姓名应该保持原样。我正在寻找一种简单快捷的更新方式。
  • 'Theme' 对象不可迭代
  • 我刚刚使用了您的第一个和平代码。有用。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 2020-11-01
  • 2018-03-26
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
相关资源
最近更新 更多