Web2py - How to update a table field appending a string to an existing field value

51 views
Skip to first unread message

Meinolf

unread,
Sep 15, 2016, 6:00:09 PM9/15/16
to web2py-users
Hi there

So far i only know how to update a record by replacing the old field value with the new value. Suppose i want to append the search_term string value the corresponding text field so that both values are stored, how can i do that in this code:

myrow = db((db.rated_items.user_id==auth.user.id) &  (db.rated_items.item_id==request.args(0))).update(search_term=str(request.vars.search_term)

Would appreciate any help!!

Massimo Di Pierro

unread,
Sep 16, 2016, 1:51:58 AM9/16/16
to web2py-users
This should work for appending strings to strings (not to lists of strings):

myrow = db((db.rated_items.user_id==auth.user.id) &  (db.rated_items.item_id==request.args(0))).update(search_term=db.rated_items.search_term+str(request.vars.search_term)

Meinolf

unread,
Sep 16, 2016, 6:44:36 AM9/16/16
to web2py-users
I had tried that and tried it just now but still gives a None value in the rated_items.search_term field. maybe it's got to do with the table def; my table definition is as follows:

db.define_table('rated_items',
    Field('search_term','string'),
    Field('user_id', 'reference auth_user', default=auth.user and auth.user.id),
    Field('item_id', 'integer'),
    Field('clicks', 'integer', default=0),
    migrate=True,
    )

Massimo Di Pierro

unread,
Sep 18, 2016, 10:59:00 PM9/18/16
to web2py-users
This works for me, I just tried:

>>> db.define_table('rated_items',

    Field('search_term','string'),

    )


>>> k = db.rated_items.insert(search_term='a')

>>> db(db.rated_items.id==k).update(search_term=db.rated_items.search_term+'b')

>>> print db.rated_items[k]

<Row {'search_term': 'ab', 'id': 1L}>


you probably have None into the search_term field and it cannot be concatenated with string.

Meinolf

unread,
Sep 19, 2016, 1:50:13 AM9/19/16
to web2py-users
Excellent, the None value was indeed the problem, so i just gave a default string value in the table definition as Field('search_term', 'string', default='') and now it works. Thanks a lot.
Reply all
Reply to author
Forward
0 new messages