On Wed, Jun 28, 2017 at 1:35 AM, Andrew M <sig...@andrewmackie.com.au> wrote:
> I can also replicate it with JSON, with a table defined as follows:
>
> class Test(Base):
>     __tablename__ = 'test'
>     id = Column(INT, primary_key=True, index=True)
>     json = Column(JSON, default={})
>
> And running the following code:
>
> p0 = Test()
> p1 = Test()
> session.add(p0)
> session.add(p1)
> session.commit()
> p0.json  # {}
> p1.json  # {}
>
> p0.json['US'] = 999
> p1.json = {'US': 999}
> p0.json == p1.json # True
>
> session.commit()
> p0.json  # {}
> p1.json  # {'US': 999}
> p0.json == p1.json # False
>
> I'm running the latest version of SQLAlchemy (1.1.11 on Python 3.6). Any
> thoughts, please?
>
> Thanks,
> Andrew

When SQLAlchemy creates a property that corresponds to a column in a
table, it sets up event listeners that are triggered whenever that
property is assigned to. The event listeners tell the SQLAlchemy
session that the object has been modified, so SA can send the changes
to the database on the next flush.

With JSON columns, the value is typically a mutable structure (a list
or a dict). They are the native Python types, so there is no mechanism
for SA to be notified when some entry in that structure changes. Since
SA doesn't see the change, it doesn't consider the object to be
modified, so the changes don't get flushed.

The fix is to not use a native Python dict for the property value, but
instead to use something that will notify SA when its contents change.
SA has an extension that provides MutableDict and MutableList classes,
as well as tools to build your own more specialized types:

http://docs.sqlalchemy.org/en/latest/orm/extensions/mutable.html

Hope that helps,

Simon

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to