SQLAlchemy按照多对多的关系排序

时间:2011-05-12 05:12:20

标签: python orm sqlalchemy flask flask-sqlalchemy

这是我当前模型的简化示例(我正在使用Flask SQLAlchemy extension

like = db.Table(
    'like',
    db.Column('uid', db.Integer, db.ForeignKey('users.id')),
    db.Column('pid', db.Integer, db.ForeignKey('posts.id'))
)

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(20))

class Post(db.Model):
    __tablename__ = 'posts'

    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(255))

    likes = db.relationship(
        'User',
        secondary = like,
        backref = db.backref('likes', lazy = 'dynamic'),
        lazy = 'dynamic'
    )

我正在尝试按照的数量订购Post

这是我基本上试图发出的查询:

SELECT p.*, COUNT(l.`pid`) as `likes`
FROM `posts` as p
LEFT JOIN `like` as l
    ON p.`id` = l.`pid`
GROUP BY p.`id`
ORDER BY `likes` DESC

我只是无法在SQLAlchemy方面做任何事情。

感谢任何人提供的帮助。

1 个答案:

答案 0 :(得分:46)

我没有太多使用SQLAlchemy所以我想我会试一试。我没有尝试使用你的模型,我只是写了一些新的(虽然类似):

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

您想要加入likes表,使用func.count来计算相似内容,group_by Post,然后使用order_by

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

我发现ORM tutorial和其他SQLAlchemy文档非常有用。