[英]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(). 并且我想基于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? 但是上面的查询是不允许的,它认为AttributeError:'Table'对象没有属性'type'根据用户拥有的最大朋友数对表格进行排序的正确方法是什么?
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.