python - from raw sql to flask-sqlalchemy -
hello im trying achieve raw query sqlalchemy:
select m.*, sum(case when f.monkey = m.id 1 else 0 end) friends monkey m left join friendship f on m.id = f.monkey group m.id, m.name order friends desc
so far result want raw query want able .paginate them keep working properly
with other queries did this:
monkeys = models.monkey.query.order_by(models.monkey.name).paginate(page, 5, false)
fairly simple , got wanted, belive have like
monkeys = models.monkey.query.join(models.friendship, db.func.count(models.monkey.id == models.friendship.monkey))
but im not getting want, know im missing sum() part tried func.c.count()but dont know how work, posible achieve in sqlalchemy? im using postgres btw
looks accomplish need
monkeys = models.monkey.query.outerjoin(models.friendship, db.func.count(models.monkey.id == models.friendship.monkey)) #or if want stick 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 doing in mysql, func.* call different
Comments
Post a Comment