我有两个型号
class Song(db.Model):
__tablename__ = 'song'
id = db.Column(db.Integer, primary_key=True)
collections = db.relationship('SongCollect', backref='song', lazy='dynamic')
class SongCollect(db.Model):
__tablename__ = 'songcollect'
id = db.Column(db.Integer, primary_key=True)
song_id = db.Column(db.Integer, db.ForeignKey('song.id'))
collect_status = db.Column(db.Boolean, default=True)
如何通过计数获取歌曲查询结果顺序(SongCollect.collect_status == True)
我使用flask-sqlalchemy。
或者我如何将以下sql翻译成sqlalchemy语法
select s.id, s.songid, s.songname,c.collect_status, sum(c.collect_status) as collect_count from song as s left join songcollect as c on s.id = c.song_id group by s.id order by collect_count desc
答案 0 :(得分:0)
# aliases: not really required
s = db.aliased(Song, name="s")
c = db.aliased(SongCollect, name="c")
# expression for the count: simple `sum` might not work on `boolean`
# types for all databases, the used option below is more robust
# collect_count = db.func.sum(c.collect_status)
collect_count = db.func.sum(db.case([(c.collect_status, 1)], else_=0))
# actual query
q = (db.session
.query(s, collect_count.label("collect_count"))
.outerjoin(c)
.group_by(s)
.order_by(collect_count.desc())
)
for song, song_collect_count in q:
print(song, song_collect_count)
print("-"*80)