我已经学习了一些教程,以便与sqlalchemy Build 多对多的关系 . 这很好用,我能够正确地插入和查询这些模型的数据 . 但是,经过相当大的努力,我无法简单地获取相关列的计数作为我的查询列之一 . 我将不胜感激任何建议 .

replications = db.Table(
    'replications',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('post_id', db.Integer, db.ForeignKey('post.id'))

)

class Post(db.Model):    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)    
    replications = db.relationship(
        'Post',
        secondary=replications,
        backref=db.backref('replicators', lazy='dynamic'),
        lazy='dynamic'
    )

# these work
print(current_user.replications.count())
print(Post.query.get(2).replicators.count())

# these do not
db.session.query(Post.id, Post.replicators.count()) # ...
db.session.query(Post.id, func.count(Post.replicators)) # ...

为了进一步解释,我想对帖子和返回的每一行进行一般性查询,请查看具有该post_id的复制表中的行数 .

我发现最接近更基本的SQL的解决方案是:

db.session.query(Post.id, func.count(distinct(Post.replicators))).outerjoin(Post.replicators).group_by(Post.id)

这有几个问题:

  • 返回的数量都比它们更大(没有复制器的所有帖子都是1,一个帖子是2,等等)

  • 性能似乎受到了相当大的影响

  • 似乎没有使用sqlalchemy ORM(它部分避开了这种关系)

寻找是否有人有更好的解决方案来执行这个相当简单的计数任务 .