banx
banx

Reputation: 4416

save_or_update using SQLalchemy 0.6

save_or_update has been removed in 0.6. Are there alternatives to use them in 0.6 and above?

I noticed the existence of the method _save_or_update_state for session objects, but there are no docs on this method.

Upvotes: 2

Views: 6009

Answers (3)

Nomad Siv
Nomad Siv

Reputation: 57

session.merge() will not work if you have your db setup as a master-slave, where you typically want to query from the slave, but write to the master. I have such a setup, and ended up re-querying from the master just before the writing, then using a session.add() if the data is indeed not there on the master.

Upvotes: -1

Denis Otkidach
Denis Otkidach

Reputation: 33200

Session.merge() works fine for both new and existing object. But you have to remember, that merge() returns object bound to the session as opposed to add() (and save_or_update() in old versions) which puts object passed as argument into the session. This behavior is required to insure there is a single object for each identity in the session.

Upvotes: 1

Sandro Munda
Sandro Munda

Reputation: 41030

Michael Bayer answered this question :

update(), save_or_update(), save() are all deprecated. add() places an object in the session in all cases, using the persistence information already associated with the object to determine INSERT or UPDATE. this means if you just make a new Foo(id=some id), that's transient - SQLAlchemy didn't load it. It will be INSERTed.

Keep in mind that the Session maintains an identity map of all unique primary keys already loaded into memory, as well as the state which was received from the database. For this reason, you generally can't just put an object in the session with some arbitrary data, and expect it to "take the place" of the actual row that would be loaded by the transaction. SQLAlchemy wouldn't know what to do with it since it has no idea what changes have been made to this row versus what is already present.

If you'd like to create a new Foo() with a primary key that may or may not already exist in the database, you want to merge the state of that object with one that is produced by the Session. Use session.merge() for this use case.
this will load the existing object from the current transaction, if any, and merge the state of your outside object with it, returning the instance. The instance you pass to it remains unchanged and outside the session.

Upvotes: 2

Related Questions