在SQLAlchemy中计数关系
我的SQLAlchemy结构是这样的:
papers2authors_table = Table('papers2authors', Base.metadata,
Column('paper_id', Integer, ForeignKey('papers.id')),
Column('author_id', Integer, ForeignKey('authors.id'))
)
class Paper(Base):
__tablename__ = "papers"
id = Column(Integer, primary_key=True)
title = Column(String)
handle = Column(String)
authors = relationship("Author",
secondary="papers2authors",
backref="papers")
class Author(Base):
__tablename__ = "authors"
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
code = Column(String, unique=True)
我想查询两个内容:
- 每篇论文的作者数量
- 每位作者的论文数量(部分答案可以在这里找到)
我尝试了很多使用func.count()
和count()
的方法,但结果都很奇怪。我该如何用SQLAlchemy来完成这两件事呢?
我尝试过的
db.s.query(func.count(core.Paper.id)).group_by(core.Author.id).first()
=sqlalchemy.exc.OperationalError: (OperationalError) no such column: authors.id
db.s.query(func.count(core.Author.papers)).group_by(core.Author.id).first()
=(128100)
,这个结果并不是我预期的db.s.query(core.Author.papers).group_by(core.Author.id).count().first()
=AttributeError: 'int' object has no attribute 'first'
- ...
1 个回答
17
找到了解决方案:
- 每篇论文有多少位作者:
db.s.query(core.Paper.title, func.count(core.Author.id)).join(core.Paper.authors).group_by(core.Paper.id).all()
- 每位作者有多少篇论文:
db.s.query(core.Author.name, func.count(core.Author.id)).join(core.Author.papers).group_by(core.Author.id).all()
相关链接: http://docs.sqlalchemy.org/en/rel_0_9/orm/query.html#sqlalchemy.orm.query.Query.having