如何查询多对多关系中的空记录

bal*_*lki 2 python sql many-to-many sqlalchemy

class BlogPost(SchemaBase):
  id = Column(Integer, primary_key=True)
  name    = Column(String,  unique=True)
  authors = relationship('Authors', secondary='authors_to_blog_post')
  __tablename__ = 'blogpost'

class Authors(SchemaBase):
  id = Column(Integer, primary_key=True)
  name    = Column(String,  unique=True)
  __tablename__ = 'author'

authors_to_blog_post = Table('authors_to_blog_post', Base.metadata,
    Column('author_id', Integer, ForeignKey('author.id')),
    Column('blogpost_id', Integer, ForeignKey('blogpost.id'))
    )
Run Code Online (Sandbox Code Playgroud)

现在如何查询没有任何作者的所有博文? session.query(BlogPost).filter(BlogPost.authors == [])不起作用

bal*_*lki 5

从这里找到答案:https://groups.google.com/d/msg/sqlalchemy/Ow0bb6HvczU/VVQbtd7MnZkJ

所以解决办法是

session.query(BlogPost).filter(~BlogPost.authors.any())
Run Code Online (Sandbox Code Playgroud)

  • 应该是`.filter(~BlogPost.authors.any())`吗? (3认同)