Misunderstanding of session or inspect

14 views
Skip to first unread message

Jim S

unread,
Feb 8, 2019, 3:22:24 PM2/8/19
to sqlalchemy
Hi

Newbie here.  I think I have a fundamental misunderstanding of either how session works or you inspect works.  My goal is to track changes to my object.  I wrote up this sample to show what I'm having trouble understanding.

from sqlalchemy import create_engine, inspect
from sqlalchemy import Column, BigInteger, String, Date, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from dateutil.relativedelta import *

Base = declarative_base()


class SaTest(Base):
    __tablename__ = 'sa_test'

    id = Column(BigInteger, primary_key=True)
    name = Column(String(50))
    dob = Column(Date)
    number_of_children = Column(Integer)

    def __repr__(self):
        return self.name


engine = create_engine('mysql://mysqluser:mysqlpassword@servername/databasename')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

"""
#  run this the first time to create the data
jim = SaTest(name='Jim', dob=parse('1971-02-23'), number_of_children=3)
session.add(jim)

joe = SaTest(name='Joe', dob=parse('1968-06-09'), number_of_children=5)
session.add(joe)

session.commit()
"""

jim = session.query(SaTest).filter_by(id=1).one()
jim.dob = jim.dob + relativedelta(days=+14)
jim.number_of_children = jim.number_of_children + 1

#joe = session.query(SaTest).filter_by(id=2).first()   <----  if I uncomment this line, inspect doesn't display the changes in history

insp = inspect(jim)

for attr, attr_state in insp.attrs.items():
    if attr_state.history.has_changes():
        print('{}: {}'.format(attr, attr_state.value))
        print('History: {}\n'.format(attr_state.history))


I've built this based on the example at the bottom of page 107 in the O'Reilly Essential SQLAlchemy book.  

It seems to my that running the second query is somehow invalidating the inspection of the jim object.  I'd really like to understand why, but haven't been able to find anything to help explain it to me.

Any help would really be appreciated.

-Jim

Mike Bayer

unread,
Feb 8, 2019, 5:53:14 PM2/8/19
to sqlal...@googlegroups.com
changes to attributes are only significant until the next flush
occurs. flushing is described at :
https://docs.sqlalchemy.org/en/latest/orm/session_basics.html#flushing.
When flush() happens, the changes to your attributes are pushed out
to the database, and the history is erased. This is because the
system only supports a "current" a "previous" value, it is only
designed to suit the purposes of session.flush(), which is to show how
the attribute differs from what is known to be in the database (in
this sense it's really not "history", it's just, "whats in the DB
right now?").

An important aspect to flushing is that the Session automatically
flushes before each query. This is called autoflush. if you want
to look at things that are affected by the flush occurring, you need
to turn it off. the docs above illustrate you can set
session.autoflush = False, but there is also a context manager that
may be more useful; the above documentation will include the link to
this manager in the next ten minutes, however it looks like:

with session.no_autoflush:
myobject.foo = bar
session.query(MyObject).all()
inspect(myobject).attrs.foo.history

direct docs for no_autoflush:
https://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=no_autoflush#sqlalchemy.orm.session.Session.no_autoflush
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
> http://www.sqlalchemy.org/
>
> To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
> ---
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
> To post to this group, send email to sqlal...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.

Jim Steil

unread,
Feb 9, 2019, 11:04:38 AM2/9/19
to sqlal...@googlegroups.com
Mike - Thanks for such a great explanation.  It is truly appreciated.

-Jim

You received this message because you are subscribed to a topic in the Google Groups "sqlalchemy" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sqlalchemy/P7iQBRipcXg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sqlalchemy+...@googlegroups.com.

Mike Bayer

unread,
Feb 9, 2019, 11:10:16 AM2/9/19
to sqlal...@googlegroups.com
As the history feature has become more known I think I've seen people have this confusion before so the docs for history should be changed to note this with a dragon.

Jim S

unread,
Feb 9, 2019, 11:12:33 AM2/9/19
to sqlalchemy
I only learned about it through the O'Reilly book.  The mention there may be the reason for it's popularity.  I didn't notice an reference to the session flush there.  Might be good to recommend a note be added to that section for newbies like me.

-Jim
Reply all
Reply to author
Forward
0 new messages