Skip to content

Instantly share code, notes, and snippets.

@batok
Created January 30, 2010 16:13
Show Gist options
  • Save batok/290608 to your computer and use it in GitHub Desktop.
Save batok/290608 to your computer and use it in GitHub Desktop.
Sqlalchemy orm how to force an update t set a = a + 1
import sqlalchemy as sa
from sqlalchemy.orm import Mapper, sessionmaker
class Example(object):
def __init__(self, field_value):
self.field_value = field_value
def __repr__(self):
return "< Example( field_value = %s ) >" % self.field_value
engine = sa.create_engine( "sqlite://", echo = True)
meta = sa.MetaData()
example_table = sa.Table("mytable", meta,
sa.Column( "id", sa.Integer, primary_key = True),
sa.Column("field_value", sa.Integer))
Mapper( Example, example_table)
meta.create_all( bind = engine )
Session = sessionmaker()
session = Session( bind = engine )
session.add( Example(field_value = 5))
session.commit()
x = session.query( Example ).one()
print x.field_value
#Now the purpose of the gist is to show how to make sqlalchemy build a query of the kind ... update mytable set field_value = ( mytable.field_value + 10 )
x.field_value = Example.field_value + 10
session.add(x)
session.commit()
y = session.query( Example ).first()
print y.field_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment