0

I do not want that my created objects are automatically persisted to Session so I found out that SQLAlchemy has an save_on_init configuration that could be set to false in order to avoid it.

But I don't know where I need to configure it. How can I configure it? Or any other way to dot not automatically persist create objects with SQLALchemy?

I just found some reference to save_on_init in older SQLAlchemy versions: http://web.mit.edu/xavid/arch/i386_linux24/tg-old/SQLAlchemy-0.4.0-py2.5.egg/sqlalchemy/orm/scoping.py

Issues with scoped_session in sqlalchemy - how does it work?

Nykolas Lima
  • 140
  • 1
  • 10
  • Could you link to the relevant docs? A quick search (and a grep around sources) yields 0 results. – Ilja Everilä Mar 14 '18 at 10:25
  • I added a few references that I found on the internet – Nykolas Lima Mar 14 '18 at 10:39
  • The first link is ancient, as is the answer referencing `save_on_init`. These days created objects are not added to a session automatically, unless you're using a modified base class that does it. The usual way is to [`Session.add()`](http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.add) objects to the session. http://docs.sqlalchemy.org/en/latest/orm/session_state_management.html is also a good read in relation. – Ilja Everilä Mar 14 '18 at 10:42
  • Yes they are automatically added to session. I'm creating a simple object: car = Car(id=None, name='corolla') Session().query(Car).all() If you run this code, when the query is executed it raises an exception saying that `ID` is null and the insert failed, but I didn't called `Session.add` to the given `car` object. You can test it locally if you want to. (And I'm not using a modified base class) – Nykolas Lima Mar 14 '18 at 10:48
  • @IljaEverilä I believe that this is happening because my class has a `relationship` with other object and this is causing the objects to be added to the Session automatically. I just don't know how to disable it. – Nykolas Lima Mar 14 '18 at 11:04
  • First of all, no I cannot verify your snippet locally. If I create such model, making my own assumptions, the new object is not added and the query returns an empty list. This is why a) you should add/edit example code in the question itself and b) provide a [mcve]. You mention an ORM relationship between the car object and some other object, so your snippet is not complete, nor verifiable. And that is indeed the reason why the car object is added to the session. Read about the [cascades](http://docs.sqlalchemy.org/en/latest/orm/cascades.html), `save-update` specifically. – Ilja Everilä Mar 14 '18 at 11:57
  • Related: ["What is the XY problem?"](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Ilja Everilä Mar 14 '18 at 12:32

0 Answers0