Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyramid: how to get id of just created db row?

In views:

model = Model('some_title', 'some text')
session.add(model)

return HTTPFound(location='/ads/%s/%s' % (model.id, model.title))

So, it must redirects me to /ads/1/some_title (if id=1), instead it redirects me to /ads/None/some_title.

How to get an id of this row after created db row in this particular example?

Thanks!

like image 549
Vitalii Ponomar Avatar asked Dec 21 '22 03:12

Vitalii Ponomar


1 Answers

at the point you ask for model.id, the new model has not yet reached the database; pyramid waits until the request handler returns before commiting the pending transaction. To get the id earlier, you must flush the session. Add:

model = Model('some_title', 'some text')
session.add(model)

session.flush()
return HTTPFound(location='/ads/%s/%s' % (model.id, model.title))
like image 138
SingleNegationElimination Avatar answered Dec 28 '22 09:12

SingleNegationElimination