简体   繁体   English

SQLAlchemy:通过辅助表以自定义条件进行外部联接

[英]Sqlalchemy: Outer join with custom condition through a secondary table

I'm trying to write a query with an outer join using a custom condition, through a secondary (many-to-many) table. 我正在尝试通过辅助表(多对多)使用自定义条件编写具有外部联接的查询。 I'm having trouble figuring out the right syntax. 我在弄清楚正确的语法时遇到了麻烦。

Let's say I have those Item and Tag tables, with a many-to-many relationship between them : 假设我有那些Item和Tag表,它们之间存在多对多关系:

item_to_tag_table = Table('item_to_tag', Base.metadata,
    Column('item_id', Integer, ForeignKey('item.id')),
    Column('tag_id', Integer, ForeignKey('tag.id')))

With the following relationship in Item : 在Item中具有以下关系:

class Item(Base):
    id = Column(Integer, primary_key=True)

    tags = relationship("Tag",
        secondary = item_to_tag_table,
        backref = "items",
        )

And I want to query items that do not contain a specific tag, so I need to use an outer join. 而且我想查询包含特定标记的项目,因此我需要使用外部联接。

If a tag was linked to only 1 item I could do something like this : 如果标签仅链接到1个项目,则可以执行以下操作:

DBSession.query(Items)\
    .outerjoin(Tag, and_(Tag.itemId == Item.id, Tag.name == "foo"))\
    .having(func.count(Tag.id) < 1)

However, for a many-to many relationship, I can't determine the right syntax: 但是,对于多对多关系,我无法确定正确的语法:

DBSession.query(Items)\
    .outerjoin(Tag, and_( ?? , Tag.name == "foo"))\
    .having(func.count(Tag.id) < 1)

Any ideas? 有任何想法吗? Do I have to make 2 outer joins, one to the secondary table, and the other to the Tag table? 我是否必须进行2个外部联接,一个联接到辅助表,另一个联接到Tag表?

Thanks in advance! 提前致谢!

In your example you don't need to use outerjoin, NOT expression is all you need ("~" before condition). 在您的示例中,您不需要使用externaljoin,仅需要NOT表达式(条件前为“〜”)。

To filter many-to-many relationship use .any() 要过滤多对多关系,请使用.any()

DBSession.query(Items)\
    .join(Tag)\ 
    .filter(~Item.tags.any(name="foo"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM