hello im trying to achieve this raw query with sqlalchemy:
SELECT m.*, SUM(case when f.monkey = m.id then 1 else 0 end) as friends
FROM monkey as m
LEFT JOIN friendship as f ON m.id = f.monkey
GROUP BY m.id, m.name
order by friends desc
so far i get the result i want with this raw query but i want to be able to .paginate them so i could keep working properly
with my other queries what i did was this:
monkeys = models.Monkey.query.order_by(models.Monkey.name).paginate(page, 5, False)
fairly simple and i got what i wanted, i belive i have to do something like
monkeys = models.Monkey.query.join(models.Friendship, db.func.count(models.Monkey.id == models.Friendship.monkey))
but im not getting what i want, i know im missing the sum() part but i tried with func.c.count()but i just dont know how to get it work, is it posible to achieve this in sqlalchemy? im using postgres btw
Looks like this will accomplish what you need
monkeys = models.Monkey.query.outerjoin(models.Friendship, db.func.count(models.Monkey.id == models.Friendship.monkey))
#or if you really want to stick to your above query
monkeys = models.Monkey.query.outerjoin(models.Friendship, db.func.SUM(func.IF(models.Monkey.id == models.Friendship.monkey, 1, 0)))
FYI I'm used to doing this in mysql, the func.* you call my be slightly different
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.