Reputation: 1293
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?
Upvotes: 4
Views: 2774
Reputation: 318508
You don't need to use add()
at all (it's only necessary for new objects). Simply modify the existing page
object and then commit.
if 'form.submitted' in request.params:
page.title = request.params['title']
page.content = request.params['content']
page.no_idea_what = datetime.now()
DBSession.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:
def do_edit_whatever(obj):
# Populate the fields here
if obj.id is None:
db.session.add(obj)
db.session.commit()
Then your view functions would call that function either with a new Page()
or one that is already in the database.
Upvotes: 6