Once some object is garbage collected by python, it disappears from the
identity map.
Example:
Set up your db:
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func
from sqlalchemy.orm import relationship, backref, joinedload
Base = declarative_base()
class Parent(Base):
__tablename__ = 'Parent'
name = Column(String(50))
gid = Column(Integer, primary_key = True)
class Child(Base):
__tablename__ = 'Child'
id = Column(Integer, primary_key = True)
loc = Column(String(50))
name = Column(String(50))
parent_gid = Column(Integer, ForeignKey('Parent.gid'))
parent = relationship("Parent", backref=backref('children'))
engine = create_engine('sqlite://', echo=True)
session = sessionmaker()
session.configure(bind=engine)
def set_up():
s = session()
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
parent = Parent(name="father")
parent2 = Parent(name="father2")
child1 = Child(name="boy1")
child2 = Child(name="girl1")
parent.children = [child1, child2]
s.add(parent)
s.commit()
set_up()
Now this works nice:
s = session()
def f(s):
print 'start f'
child = s.query(Child).first()
parents = s.query(Parent).all() # load all parents objects in identity map
child.parent # this will not issue SQL because parents are in identity map
print 'end f'
return child
child = f(s)
This does not
s = Session()
def f(s):
print 'start f'
child = s.query(Child).first()
parents = s.query(Parent).all() # load all parents objects in identity map
print 'end f'
return child
child = f(s)
child.parent # will issue SQL because parents has disappeared from identity
map
I would like to force the identity map to save some objects even after
garbage collection
Le jeudi 21 juillet 2016 16:48:55 UTC+2, Simon King a écrit :
>
> On Thu, Jul 21, 2016 at 3:29 PM, Mehdi gmira <[email protected]
> <javascript:>> wrote:
> > Is there a way to explicitely add objects to the identity map ? I would
> like
> > to be able to do something like:
> >
> > foos = session.query(Foo).all()
> > add_to_identity_map(foos)
>
> I don't understand the question - objects loaded by session.query are
> *already* in the identity map for that session.
>
> If you have an object that wasn't loaded from the session originally,
> I think the official answer is session.merge(), although that returns
> a new object. Would that work in your instance?
>
> Simon
>
--
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.