SQLAlchemy ordering by count on a many to many relationship

前端 未结 1 420
闹比i
闹比i 2020-11-30 05:47

This is a simplified example of my current models (I\'m using the Flask SQLAlchemy extension):

like = db.Table(
    \'like\',
    db.Column(\'uid\',         


        
相关标签:
1条回答
  • 2020-11-30 06:24

    I haven't used SQLAlchemy much so I figured I'd give it a shot. I didn't try to use your models, I just wrote some new ones (similar enough though):

    likes = db.Table('likes',
        db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
        db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
    )
    
    class User(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(20))
    
        def __repr__(self):
            return "<User('%s')>" % self.username
    
    class Post(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(255))
    
        likes = db.relationship('User', secondary = likes,
            backref = db.backref('posts', lazy='dynamic'))
    
        def __repr__(self):
            return "<Post('%s')>" % self.title
    

    You want to join the likes table, use func.count to count likes, group_by Post and then use order_by:

    db.session.query(Post, func.count(likes.c.user_id).label('total')).join(likes).group_by(Post).order_by('total DESC')
    

    I found the ORM tutorial and the rest of the SQLAlchemy documentation very useful.

    0 讨论(0)
提交回复
热议问题