SQLAlchemy: Inconsistent behaviour after commit
<p>I have a SQLAlchemy ORM, whose <code>__str__()</code> function prints a table of keys and values.
The following code commits it to the DB and prints it (attribute names changed for clarity):</p>

<pre><code>user.some_attribute = &lt;Some integer&gt;
session.add(user)
session.commit()
app.logger.debug("some_attribute is %s" % user.some_attribute)
app.logger.debug("Created a DB row:\n%s" % user)
</code></pre>

<p><strong>The crazy thing here is that the second debug print only works if the first debug exists!</strong></p>

<p>In other words, if the two debug lines exist, I get:</p>

<pre><code>some_attribute is 5
+------------------------------------------+-------------------------------------------------+
| Field                                    | Value                                           |
+------------------------------------------+-------------------------------------------------+
| creation_time                            | 2016-09-26 15:25:45.630230                      |
| description                              | Test Poly 835                                   |
| destination_truck_ids                    | ['A']                                             |
| future_event_series_id                   | None                                            |
| id                                       | 1017                                            |
...
</code></pre>

<p>But if only the second one is present, I get:</p>

<pre><code>+-------+-------+
| Field | Value |
+-------+-------+
+-------+-------+
</code></pre>

<p><strong>Why does the ORM have no attributes, unless one of its features is printed?</strong> </p>

<p>I found a workaround, even though I'm not really sure about the nature of the problem.</p>

<p>Quoting <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.commit" rel="nofollow">the manual</a>:</p>

<blockquote>
  <p>By default, the Session also expires all database loaded state on all
  ORM-managed attributes after transaction commit. This so that
  subsequent operations load the most recent data from the database.
  This behavior can be disabled using the expire_on_commit=False option
  to sessionmaker or the Session constructor.</p>
</blockquote>

<p>If I load the session with <code>expire_on_commit=False</code>, the problem is solved - I get the ORM even after the commit.</p>

python session orm sqlalchemy