Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last insert id with SQLAlchemy

I'm using SQLAlchemy

import hashlib
import sqlalchemy as sa
from sqlalchemy import orm

from allsun.model import meta


t_user =  sa.Table("users",meta.metadata,autoload=True)

class Duplicat(Exception):
 pass
class LoginExistsException(Exception):
 pass
class EmailExistsException(Exception):
 pass

class User(object):
 """
 def __setattr__(self, key, value):
  if key=='password' :
   value=unicode(hashlib.sha512(value).hexdigset())
   object.__setattr__(self,key,value)
"""
 def loginExists(self):
  try:
   meta.Session.query(User).filter(User.login==self.login).one()
  except orm.exc.NoResultFound:
   pass
  else:
   raise LoginExistsException()

 def emailExists(self):
  try:
   meta.Session.query(User).filter(User.email==self.email).one()
  except orm.exc.NoResultFound:
   pass
  else:
   raise EmailExistsException()


 def save(self):
  meta.Session.begin()
  meta.Session.save(self)
  try:
   meta.Session.commit()
  except sa.exc.IntegrityError:
   raise Duplicat()

How can I get the last inserted id when I call:

user = User()
user.login = request.params['login']
user.password = hashlib.sha512(request.params['password']).hexdigest()
user.email = request.params['email']
user.save()
like image 222
gummmibear Avatar asked Apr 11 '10 21:04

gummmibear


1 Answers

You can access user.id (or whatever name you use for autoincremeted primary key field) after saving user object. SQLAlchemy automatically fills fields assigned by database.

like image 83
Denis Otkidach Avatar answered Sep 17 '22 12:09

Denis Otkidach