dynamic keywords on database update

26 views
Skip to first unread message

mmstud

unread,
Feb 22, 2012, 2:24:34 PM2/22/12
to web2py-users
Hi,

I have a simple question in turn. How is it possible to make keyword
search criteria dynamic? For example:

db(Orders.id==id).update(Keyword+n = checked)

where n is any number?

Anthony

unread,
Feb 22, 2012, 2:33:00 PM2/22/12
to web...@googlegroups.com
db(Orders.id==id).update(**{'%s%s' % (Keyword, n): checked})

Anthony 

Mchurch

unread,
Feb 23, 2012, 2:27:44 AM2/23/12
to web2py-users
**{'%s%s' % (Keyword, n): checked})
Anthony, can you explain it better? It's something that I would like
to understand very well.
Tnx.

Anthony

unread,
Feb 23, 2012, 9:19:36 AM2/23/12
to web...@googlegroups.com
On Thursday, February 23, 2012 2:27:44 AM UTC-5, Mchurch wrote:
**{'%s%s' % (Keyword, n): checked})
Anthony, can you explain it better? It's something that I would like
to understand very well.

'%s%s' % (Keyword, n) is Python string formatting -- if Keyword is "hello" and n is 5, it will produce the string "hello5". Now, suppose "checked" is a boolean value equal to True -- then the above will produce the following dictionary:

{hello5: True}

In Python, you can pass a dictionary to a function and precede it with **, and that is equivalent to passing each item in the dictionary to the function as a separate keyword argument. So,

update(**{hello5: True})

is equivalent to

update(hello5=True)

Of course, the "hello5" is generated dynamically, so we can't use the latter syntax, but we can construct a dictionary with a dynamically generated key, which enables us to use the former syntax.

Anthony

Mchurch

unread,
Feb 23, 2012, 10:33:26 AM2/23/12
to web2py-users
thanks a lot!

Wikus van de Merwe

unread,
Feb 23, 2012, 11:14:23 AM2/23/12
to web...@googlegroups.com
You can pass a dictionary to a function as if you are passing keyword arguments.
kwargs = {"a":1, "b":2}
f(**kwargs)  # this call is equal to f(a=1, b=3)

There is similar mechanism for positional arguments in Python:
args = [1, 2]
f(*args)  # this call is equal to f(1, 2)

Reply all
Reply to author
Forward
0 new messages