Skip to content

Instantly share code, notes, and snippets.

@clavery
Created March 26, 2014 05:07
Show Gist options
  • Save clavery/9777210 to your computer and use it in GitHub Desktop.
Save clavery/9777210 to your computer and use it in GitHub Desktop.
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.functions import coalesce
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, select
from sqlalchemy import create_engine
from sqlalchemy import func
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base()
class Foo(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
num = Column(Integer)
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)
foo = Foo()
foo.num = select([coalesce(func.max(Foo.num), 0) + 1]).where(Foo.id > 0)
session.add(foo)
session.commit()
foos = session.query(Foo).all()
print foos[0].num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment