Created
July 17, 2012 19:50
-
-
Save podhmo/3131587 to your computer and use it in GitHub Desktop.
how to use session.merge [sqlalchemy]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[<__main__.Sub object at 0x1f44250>, <__main__.Sub object at 0x1f44390>, <__main__.Sub object at 0x1f44350>] | |
[u'a', u'b', u'c'] | |
pre commit | |
------ | |
ok | |
after commit | |
------ | |
Parent instance <Main at 0x1f3d190> is not bound to a Session; lazy load operation of attribute 'subs' cannot proceed | |
session merge | |
------ | |
Parent instance <Main at 0x1f3d190> is not bound to a Session; lazy load operation of attribute 'subs' cannot proceed | |
ok |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlalchemy as sa | |
import sqlalchemy.orm as orm | |
import sqlahelper | |
from sqlalchemy.ext.associationproxy import association_proxy | |
base = sqlahelper.get_base() | |
class Main(base): | |
id = sa.Column(sa.Integer, primary_key=True) | |
name = sa.Column(sa.Unicode(255)) | |
__tablename__ = "main" | |
subbox = association_proxy("subs", "name", creator=lambda name: Sub(name=name)) | |
class Sub(base): | |
id = sa.Column(sa.Integer, primary_key=True) | |
main_id = sa.Column(sa.Integer, sa.ForeignKey("main.id")) | |
main = orm.relationship("Main", backref="subs") | |
name = sa.Column(sa.Unicode(255)) | |
__tablename__ = "sub" | |
engine = sa.create_engine("sqlite://") | |
sqlahelper.add_engine(engine) | |
base.metadata.create_all() | |
session = sqlahelper.get_session() | |
main = Main(name=u"foo") | |
main.subbox.append(u"a") | |
main.subbox.append(u"b") | |
main.subbox.append(u"c") | |
def use_lookup(main): | |
try: | |
main.subs | |
print "\tok" | |
except Exception, e: | |
print "\t%s" % e | |
pass | |
def section(mes): | |
print mes | |
print "------" | |
print [s for s in main.subs] | |
print [s.name for s in main.subs] | |
print "\n\n" | |
session.add(main) | |
section("pre commit") | |
use_lookup(main) | |
import transaction | |
transaction.commit() | |
section("after commit") | |
use_lookup(main) | |
### session.merge | |
section("session merge") | |
merged = session.merge(main) | |
use_lookup(main) | |
use_lookup(merged) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment