Max
Max

Reputation: 2475

How to sort a table by maximum value of a column using flask/sqlalchemy?

I have a self referential talbe with bellow User class:

class User(db.Model): 
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(50), unique = True)
password = db.Column(db.String(50))
email = db.Column(db.String(100), index = True, unique =True)
age = db.Column(db.SmallInteger())
about_user = db.Column(db.String(500))
img_url = db.Column(db.String(120))

    is_friend = db.relationship('User',
    secondary = friends, 
    primaryjoin = (friends.c.user_id == id),
    secondaryjoin = (friends.c.friend_id == id), 
    backref = db.backref('friends', lazy = 'dynamic'), 
    lazy = 'dynamic')

and I would like to sort the query based on the maximum number of is_friend(). The query must be something like bellow:

User.query.order_by(func.max(User.is_friend)).paginate(page, MONKEYS_PER_PAGE, False)

but the above query is not allowable it argues that AttributeError: 'Table' object has no attribute 'type' What is the right way to sort the table based on the maximum number of friend that a user have?

Upvotes: 0

Views: 1263

Answers (1)

davidism
davidism

Reputation: 127180

# count the number of friends for each user
# friends are users as well, so need alias
# construct subquery for use in final query

friend = db.aliased(User)

sub = db.session.query(
    User.id,
    db.func.count(friend.id).label('fc')
).join(friend, User.friends
).group_by(User.id).subquery()

# query users, join on subquery to get friend count
# order by friend count, descending

users = db.session.query(User
).join(sub, sub.c.id == User.id
).order_by(sub.c.fc.desc()
).paginate(page, MONKEYS_PER_PAGE, False)

Upvotes: 3

Related Questions