按数对多关系进行排序,而不返回带数的元组

时间:2018-11-02 20:12:04

标签: python sqlalchemy

具有以下简化的类和表

tags = db.Table(
        "tags",
        db.Column("tag_id", db.Integer, db.ForeignKey("tag.id")),
        db.Column("post_version_id", db.Integer, db.ForeignKey("post_version.id"))
        )

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)

class PostVersion(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    current = db.Column(db.Boolean, default=False, index=True)

我正在尝试通过Tag的数量排序的所有PostVersion发出呼叫,这些数量都通过tags连接并且拥有值current=True

我已经开发了以下查询:

db.session.query(Tag,
        db.func.count(PostVersion.id).label("total")
        ).outerjoin(tags
        ).outerjoin(PostVersion,    
                and_(PostVersion.id==tags.c.post_version_id,
                PostVersion.current==True)
        ).group(Tag).order_by("total DESC").all()

产生以下(正确)结果:

[(<Tag 8: original>, 136),
 (<Tag 16: constance-garnett>, 136),
 (<Tag 3: explanation>, 3),
 (<Tag 2: definition>, 1),
 (<Tag 14: translation>, 1),
 (<Tag 1: biblical>, 0),
 (<Tag 4: homage>, 0),
 (<Tag 5: intertextuality>, 0),
 (<Tag 6: meter>, 0),
 (<Tag 7: mythology>, 0),
 (<Tag 9: political>, 0),
 (<Tag 10: cultural>, 0),
 (<Tag 11: reference>, 0),
 (<Tag 12: shakespeare>, 0),
 (<Tag 13: technical-issues>, 0),
 (<Tag 15: context>, 0)]

除了,为了抑制基于元组的输出(其中包含db.func.count(PostVersion.id).label("total")的结果,我必须对结果进行其他修改,而且我完全不确定如何重写查询来抑制这种情况。

如何将查询表述为仅按查询返回的顺序返回对象?

1 个答案:

答案 0 :(得分:1)

解决方案很简单:将count表达式移至ORDER BY子句:

db.session.query(Tag).\
    outerjoin(tags).\
    outerjoin(PostVersion,
              and_(PostVersion.id==tags.c.post_version_id,
                   PostVersion.current==True)).\
    group_by(Tag.id).\
    order_by(db.func.count(PostVersion.id).desc()).\
    all()