Why SQLAlchemy send extra SELECTs when accessing a persisted model property
<p>Given a simple declarative based class;</p>

<pre><code>class Entity(db.Model):

    __tablename__ = 'brand'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
</code></pre>

<p>And the next script</p>

<pre><code>entity = Entity()
entity.name = 'random name'
db.session.add(entity)
db.session.commit()

# Just by accessing the property name of the created object a
# SELECT statement is sent to the database.

print entity.name
</code></pre>

<p>When I enable <code>echo</code> mode in SQLAlchemy, I can see in the terminal the <strong><code>INSERT</code></strong> statement and an extra <strong><code>SELECT</code></strong> just when I access a property (column) of the model (table row).</p>

<p>If I don't access to any property, the query is not created.</p>

<p>What is the reason for that behavior? In this basic example, We already have the value of the <code>name</code> property assigned to the object. So, Why is needed an extra query? It to secure an up to date value, or something like that?</p>

<p>By default, SQLAlchemy expires objects in the session when you commit. This is controlled via the <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.params.expire_on_commit" rel="nofollow"><code>expire_on_commit</code></a> parameter.</p>

<p>The reasoning behind this is that the row behind the instance could have been modified outside of the transaction, so if you are not careful you could run into data races, but if you know what you are doing you can safely turn it off.</p>

python sqlalchemy flask-sqlalchemy