Вопрос

Is it possible, in Python using peewee + MySQL database, to use some variable as keyword in update function?

For example:

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()

If we have table like this:

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'
Это было полезно?

Решение

Yes, you can pass an unpacked dictionary as a keyword argument, like so:

update = Users.update(**{what: value}).where(Users.id == some_user_id)

Example of how it works:

>>>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}

Related question

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top