python - SQLAlchemy count followers to a tag -
say have tag model:
class tag(db.model): id = db.column(db.integer, primary_key = true) name = db.column(db.string(240)) def followerranked(self): #return query(followers, func.count(followers.c.tag_id)).outerjoin(tag)?? #return tag.query.join(followers, (followers.c.tag_id == self.id).count()?? #i not sure how
say have subscriptions table relationship.
followers = db.table('followers', db.column('follower_id', db.integer, db.foreignkey('user.id')), db.column('tag_id', db.integer, db.foreignkey('tag.id')) )
i want loop through tags... in desc order number of followers per tag. think need group_by somewhere.
i want able loop through:
tags.followersranked().items
how do this?
edit:
apparently, becomes difficult in model, i'm trying in view instead:
tags = db.session.query(models.tag, \ func.count(models.followers.c.follower_id).label('total'), models.tag.name, \ models.tag.title).join(models.followers).group_by(models.tag).order_by('total desc') p = pagination(tags, page, posts_per_page, tags.count(), tags)
the issue is, doesn't show tags 0 subscribers.
change join()
outerjoin()
, use coalesce()
change null
s 0
s:
tags = db.session.query( db.coalesce(db.func.count(models.followers.c.follower_id), 0).label('total'), models.tag.name, models.tag.title ).outerjoin(models.followers).group_by( models.tag.name, models.tag.title ).order_by('total desc')
that should trick.
Comments
Post a Comment