python - SqlAlchemy: Join onto another object -
my little website has table of comments , table of votes. each user of website gets vote once on each comment.
when displaying comments user, select comments table , outerjoin vote if 1 exists current user.
is there way make query vote attached comment through comment.my_vote ?
the way i'm doing now, query returning list each result - [comment, vote] - , i'm passing directly template. i'd prefer if vote child object of comment.
setup model add one-to-one relationship. sample code link verbatim:
class parent(base): __tablename__ = 'parent' id = column(integer, primary_key=true) child = relationship("child", uselist=false, backref="parent", # lazy='joined', # @note: optional: uncomment have 'child' loaded when parent loaded. ) class child(base): __tablename__ = 'child' id = column(integer, primary_key=true) parent_id = column(integer, foreignkey('parent.id'))
in case parent
comment
, child
vote
.
can query comment
, @ same time eagerly loading vote
. recomment uncomment commented out line above, query return in 1 sql
statement. alternatively can specify loading of vote
in query explicitly using joinedload
:
res = query(parent).options(joinedload(parent.child))
Comments
Post a Comment