Skip to content

Instantly share code, notes, and snippets.

@tehasdf
Last active August 26, 2016 13:55
Show Gist options
  • Save tehasdf/e33ff6f13dac24a5523f55d68fda2fea to your computer and use it in GitHub Desktop.
Save tehasdf/e33ff6f13dac24a5523f55d68fda2fea to your computer and use it in GitHub Desktop.
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey, create_engine
from sqlalchemy.orm import relationship, Session, backref
Base = declarative_base()
eng = create_engine('postgresql+psycopg2:///asdf', echo=True)
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey(Parent.id))
parent = relationship(
Parent,
lazy='joined',
backref=backref(
'children',
lazy='joined')
)
Base.metadata.drop_all(eng)
Base.metadata.create_all(eng)
s = Session(bind=eng)
s.add(Parent(id=1))
s.add(Child(id=1, parent_id=1))
c = s.query(Child).all()
s.close()
print c[0].parent # works just fine because parent was joined by default using `lazy='joined` in rel
print c[0].parent.children # throws
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment