【问题标题】:Counting relationships in SQLAlchemy计算 SQLAlchemy 中的关系
【发布时间】:2014-10-19 11:43:38
【问题描述】:

我的 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)

我想查询两件事:

  1. 每篇论文的作者人数
  2. 每位作者的论文数量(部分回答here

我用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'
  • ...

【问题讨论】:

标签: python sql sqlalchemy


【解决方案1】:

找到解决方案:

  1. 每篇论文的作者数量:db.s.query(core.Paper.title, func.count(core.Author.id)).join(core.Paper.authors).group_by(core.Paper.id).all()
  2. 每位作者的论文数量: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

【讨论】:

    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2013-10-22
    • 2013-06-23
    • 1970-01-01
    相关资源
    最近更新 更多