Peewee SQL 查询加入 none 的许多匹配项

Peewee SQL query join where none of many match

以下 SQL 查找没有任何名为 'BadTag'.

的关联标签的所有帖子
select * from post t1
where not exists
(select 1 from tag t2
   where t1.id == t2.post_id and t2.name=='BadTag');

如何在 Peewee ORM 中编写此功能?如果我按照

的方式写一些东西
Post.select().where(
    ~Tag.select()
    .where(Post.id == Tag.post & Tag.name=='BadTag')
    .exists()
)

它被编译为

SELECT "t1"."id", ... FROM "post" AS t1 WHERE ? [-1]

类似

Post.select().join(Tag).where(Tag.name!='BadTag')

不起作用,因为 Post 可以有很多标签。

我是 SQL/Peewee 的新手,所以如果这是一种糟糕的处理方式,我欢迎指点。

不要使用 manecosta 的解决方案,效率低下。

以下是如何使用子查询执行 NOT EXISTS:

(Post
 .select()
 .where(~fn.EXISTS(
      Tag.select().where(
          (Tag.post == Post.id) & (Tag.name == 'BadTag'))))

您也可以加入:

(Post
 .select(Post, fn.COUNT(Tag.id))
 .join(Tag, JOIN.LEFT_OUTER)
 .where(Tag.name == 'BadTag')
 .group_by(Post)
 .having(fn.COUNT(Tag.id) == 0))