How to prevent new objects from being automatically attached to scoped_session?

39 views
Skip to first unread message

Eloff

unread,
Oct 3, 2009, 2:30:59 PM10/3/09
to SQLElixir
I asked about this on #sqlalchemy a while back, and the answer IIRC is
that it has to do with something elixir is passing (or not passing)
during the creation of the tables and mappers. Apparently it's not
recommended practice in sqlalchemy.

That being as it may be, how can I change this behavior? I usually
explicitly add objects to the session when I mean to, and I often keep
local sessions around to prevent unrelated queries from being lumped
into one transaction. Often that means I need to explicitly remove an
object from the scoped_session, and add it to the local session after
creation.

class Foo(Entity):
pass

s = LocalSession()
f = Foo()
s.add(f) # ERROR object already attached to a session

I want to say that I've been very happy with elixir overall, it has
been very stable and well thought out, and I've not had many
surprises.

Thanks,
-Dan

Gaetan de Menten

unread,
Oct 4, 2009, 9:43:51 AM10/4/09
to sqle...@googlegroups.com
On Sat, Oct 3, 2009 at 20:30, Eloff <dan....@gmail.com> wrote:

> I asked about this on #sqlalchemy a while back, and the answer IIRC is
> that it has to do with something elixir is passing (or not passing)
> during the creation of the tables and mappers. Apparently it's not
> recommended practice in sqlalchemy.
>
> That being as it may be, how can I change this behavior? I usually
> explicitly add objects to the session when I mean to, and I often keep
> local sessions around to prevent unrelated queries from being lumped
> into one transaction. Often that means I need to explicitly remove an
> object from the scoped_session, and add it to the local session after
> creation.
>
> class Foo(Entity):
>     pass
>
> s = LocalSession()
> f = Foo()
> s.add(f) # ERROR object already attached to a session

There are several options...

The most granular one, but also the most tedious, is to use

using_mapper_options(save_on_init=False)

in each of your entities where you don't want that behavior.

For an example, see:
http://elixir.ematia.de/trac/browser/elixir/tags/0.7.0/tests/test_options.py#L159

If you don't want to specify that on a per-entity basis, you could add
the following line before you declare your entities:

elixir.options_defaults['mapper_options'] = {'save_on_init': False}

or, if you don't want to use the default session at all, you can add:

__session__ = None

at the beginning of the module(s) where your entities are declared.

Hope it helps,
--
Gaëtan de Menten
http://openhex.org

Reply all
Reply to author
Forward
0 new messages