V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
tomleung1996
V2EX  ›  问与答

SQLAlchemy 如何对一对多关系进行 COUNT 计数?

  •  1
     
  •   tomleung1996 · 2019-01-26 15:26:55 +08:00 · 1044 次点击
    这是一个创建于 1910 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题描述

    我用 SQLAlchemy 建了一个 SQLite 数据库来存文献数据,现在我想查每一篇文献的作者数量,作者和文献是分开两张表存的,用文献的识别号来建立联系

    我知道用 SQL 怎么查询,但是现在我想用 SQLAlchemy 来操作,不使用纯 SQL

    文献和作者对象的定义代码如下:

        class WosDocument(Base):
            __tablename__ = 'wos_document'
    
            document_id = Column(Integer, primary_key=True)
            unique_id = Column(String, unique=True)
            ......
            authors = relationship('WosAuthor', back_populates='document')
    
        class WosAuthor(Base):
            __tablename__ = 'wos_author'
    
            author_id = Column(Integer, primary_key=True, autoincrement=True)
    
            document_unique_id = Column(String, ForeignKey('wos_document.unique_id'))
            document = relationship('WosDocument', back_populates='authors')
    
            last_name = Column(String)
            first_name = Column(String)
    

    我希望查询得到的结果和这个 SQL 相同,返回每一篇文章的识别号及其作者数

         SELECT a.unique_id, COUNT(*) 
         FROM wos_document AS a 
         LEFT JOIN wos_author AS b 
         ON a.unique_id = b.document_unique_id 
         GROUP BY a.unique_id
    

    但是用了 ORM 之后我可以通过WosDocument.authors来获得一篇文章的全部作者信息,于是我就想是不是能够不使用join也能达到同样的效果?于是我尝试了下面的代码:

        session.query(WosDocument.unique_id, len(WosDocument.authors)).all()
    
        session.query(WosDocument.unique_id, func.count(WosDocument.authors)).all()
    

    第一种方式直接就报错无法执行,第二种方式只返回了一行结果,我也理解不了结果的含义是什么

    [('000275510800023', 40685268)]
    

    我想问用 SQLAlchemy 的正确写法是什么?可以不使用连接查询吗?谢谢大家!

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   865 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 21:41 · PVG 05:41 · LAX 14:41 · JFK 17:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.