在使用peewee + MySQL数据库的Python中,是否有可能在更新函数中使用某个变量作为关键字?
例如:
what = raw_input('What you want to change? name, surname, email ')
value = raw_input('What is the value?')
update = Users.update(what=value).where(Users.id == some_user_id)
update.execute()
如果我们有这样的表:
class Users(BaseModel):
email = CharField(max_length=50, null=True)
name = CharField(max_length=50, null=True)
surname = CharField(max_length=50, null=True)
class Meta:
db_table = 'users'
答案 0 :(得分:2)
是的,您可以将解压缩的dictionary作为关键字参数传递,如下所示:
update = Users.update(**{what: value}).where(Users.id == some_user_id)
它的工作原理示例:
>>>def foo(a=2):
... print a
...
>>>foo(**{'a': 3})
3
>>>b = 'a'
>>>foo(**{b: 4})
4
>>>foo(**{'c': 5})
TypeError: f() got an unexpected keyword argument 'c'
>>>foo({'a': 6})
{'a': 6}