SqlAlchemy,如何进行自动连接

时间:2017-05-18 13:41:50

标签: python sqlalchemy

我有3张桌子

class Article_Comment(Base):
    __tablename__ = 'article_comment'
    article_id = Column(Integer, ForeignKey('article.id'), primary_key=True)
    comment_id = Column(Integer, ForeignKey('comment.id'), primary_key=True)
    child = relationship("Comment",  lazy="joined", innerjoin=True)


class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True)
    title = Column(String)
    children = relationship("Article_Comment", lazy="joined", innerjoin=True)


class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True)
    text = Column(String)

我需要获得具有评论的特定文章。我是这样做的:

Session = sessionmaker(bind=engine)
session = Session()
result = session.query(Article, Comment).join(Article_Comment).join(Comment).filter(Article_Comment.article_id == Article.id).filter(Article_Comment.comment_id == Comment.id).filter(Article.title=='music').all()
for i, j in result:
    print i.title, j.text

但我想在不使用.join的情况下进行此查询。

有人可以帮助我吗?

可能,我需要重拍关系吗?

1 个答案:

答案 0 :(得分:0)

我的 univerio

以下是完整的答案

Articlecomments = relationship(Comment, secondary=Article_Comment.__table__, lazy="joined")

上设置关系
session.query(Article).filter(Article.title=='music').one().‌​comments