How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two?

前端 未结 1 1705
天命终不由人
天命终不由人 2021-01-04 20:17

Suppose I have the following tables:

  • Articles with fields article_id, title
  • Tags with fields
相关标签:
1条回答
  • 2021-01-04 20:50

    Assuming that you set the ForeignKey constraints correctly and created mappers:

    q = Session.query(Articles).filter(Articles.article_id == ArticleTags.article_id).\
        filter(ArticleTags.tag_id == Tags.tag_id).\
        filter(Tags.name == 'tag_name')
    

    If you have setup a Many-to-Many relation it's even more simple:

    q = Session.query(Articles).filter(Articles.tags.any(name = 'tag_name'))
    

    For some more examples for blog-related queries look here.

    If you use the sql expression language, it should be straight forward translateable.

    0 讨论(0)
提交回复
热议问题