如何使用flask / sqlalchemy按列的最大值对表进行排序?

时间:2014-04-17 22:50:01

标签: python sqlalchemy flask flask-sqlalchemy

我有一个自我引用的用户类:

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')

我想根据is_friend()的最大数量对查询进行排序。查询必须类似于下面的内容:

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

但上述查询是不允许的,它认为 AttributeError:'表'对象没有属性'键入' 根据用户拥有的最大朋友数量对表格进行排序的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

# 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)