How can I update a row in my database using add() ?
Here is the code I tried :
@view_config(route_name='doc_user_edit', renderer='doc/edit.mako')
def doc_user_edit(request):
""" Edit a documentation page. """
message = ""
try:
page = DBSession.query(Page).filter_by(title=request.matchdict['pagename']).first()
except DBAPIError:
return Response('An error occured while trying to contact the database', content_type='text/plain', status_int=500)
if page is None:
return HTTPNotFound('No such page')
if 'form.submitted' in request.params:
page = Page(request.params['title'], request.params['content'], datetime.now())
DBSession.add(page)
DBSession.commit()
message = _('Page edited')
return {'p':page,
'm':message,
'save_url': request.route_url('doc_user_edit', pagename=page.title),
}
Notes : DBSession is a scoped_session.
If the row is brand new (i.e. unique key “title” is not present), it correctly adds a new row with the values I passed to it.
But if the row is an existing one, it simply does… nothing. I’d like it to update the row with new values (i.e. values extracted from a form). How can I achieve that?
You don’t need to use
add()at all (it’s only necessary for new objects). Simply modify the existingpageobject and then commit.By the way, unless there is a really good reason to use localtime it’s better to store your timestamps in UTC.
Depending on how your site works you might want to combine the logic for edit and create though. It would basically look like this:
Then your view functions would call that function either with a new
Page()or one that is already in the database.