Ant*_*nko 8 python sql 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)
Run Code Online (Sandbox Code Playgroud)
我想查询两件事:
我试着用很多选项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.iddb.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'找到解决方案:
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
| 归档时间: |
|
| 查看次数: |
5364 次 |
| 最近记录: |