On Dec 26, 2007 10:38 PM, Michael Bayer <[EMAIL PROTECTED]> wrote:
> if you have an instance which you are unsure if it already exists, you
> can add it to a session using session.save_or_update(instance). The
> decision between INSERT and UPDATE is ultimately decided by the
> presence of an attribute on the instance called "_instance_key".
I'd like mapper to use UPDATE for newly constructed object (i.e.
object without _instance_key attribute) when a record with the same
primary key already exists in DB.
> In most cases, this attribute is not something you need to worry about;
> if an instance has been flushed or loaded from a session, it will have
> the attribute, or if you've just constructed it and not yet persisted
> it, the attribute will not be there. If you think you need to
> manually manipulate this attribute, perhaps you can describe your
> specific use case so that we can recommend the best way to accomplish
> it.
OK, below is a use/test case:
--->8---
import sqlalchemy as sa, logging
from sqlalchemy.orm import mapper, sessionmaker
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
logging.basicConfig()
class ModelObject(object):
def __init__(self, id, title):
self.id = id
self.title = title
metadata = sa.MetaData()
objectTable = sa.Table(
'Objects', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('title', sa.String(255), nullable=False),
)
objectsMapper = mapper(ModelObject, objectTable)
engine = sa.create_engine('sqlite://')
metadata.create_all(engine, checkfirst=True)
session = sessionmaker(bind=engine)()
obj = ModelObject(1, u'title')
session.save(obj)
session.commit()
session.clear()
# Another program. We have to insure that object with id=1 exists in DB and has
# certain properties.
obj = ModelObject(1, u'title')
session.save_or_update(obj)
session.commit()
--->8---
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---