Skip to content

Instantly share code, notes, and snippets.

Created March 5, 2020 14:11
What would you like to do?
SQLAlchemy demonstration of the "FetchedValue" feature
This file demonstrated using the "FetchedValue" feature of SQLAlchemy for
values which are generated by the DB, without knowing *how* they are generated
in the DB.
from sqlalchemy import Column, DateTime, FetchedValue, Unicode, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Foo(Base):
__tablename__ = "foo"
# mapper-args are necessary to tell SA to use the "RETURNING" statements.
# Note that this will cause overhead on DBs which don't support "RETURNING"
__mapper_args__ = {"eager_defaults": True}
name = Column(Unicode, primary_key=True)
# Assuming the server assigns a value by default, using "FetchedValue"
# marks this column as a column that should be added in a "RETURNING"
# statement. On DBs not supporting "RETURNING", this will cause an
# additional SELECT
created = Column(DateTime, server_default=FetchedValue())
engine = create_engine('postgresql://malbert@/malbert', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
instance = Foo(name="foo")
session.flush() # Flush is needed. FetchedValue does not trigger autoflush
print('>>---', instance.created)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment