我有一个带有postgresql的flask应用程序,我想根据用户的好友名称对其进行排序。为了解释数据库,它在《老友记》中有一对一的关系,我使用了flask migrate和Alembic。但出现了这个错误,如果你能告诉我如何解决它,问题在哪里?
错误
sqlalchemy.exc.编程错误
ProgrammingError:(ProgrammingError)列";users_1.name";必须出现在GROUP BY子句中,或在聚合函数LINE 2:FROM用户加入(选择users.name作为名称,users_1.name作为
…^'选择users.id AS users_id,users.name AS users_name,users.age AS users_age、users.email AS users_email,users.bestfriend_id AS users_bestfriend-id\nFROM用户加入(选择users.name AS name,users_1.name AS fn\nFROM users JOIN users ASusers_1 ON users_1.id=users.bestfriend_id GROUP BY users.name)ASanon_1 ON anon_1.name=users.name ORDER BY anon_1.fn ASC\n LIMIT%(param_1)s偏移%(param_2)s'{'param_1':2,'param_2':0}
model.py:
friends = db.Table('friends',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column('friend_id', db.Integer, db.ForeignKey('users.id'))
)
class Users(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50), index=True)
age= db.Column(db.Integer )
email = db.Column(db.String(50),index=True, unique= True)
bestfriend_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete ='SET NULL'), nullable=True)
is_bestfriend = db.relationship( 'Users', uselist=False, remote_side=[id], post_update=True)
view.py
#condition to sort base on bestfriend name
elif request.args.get('sort') == 'bf':
sortBy = 'bf'
friend = db.aliased(Users)
sub = db.session.query(
Users.name, friend.name.label('fn')).
join(friend, Users.is_bestfriend).group_by(Users.name).subquery()
monkey = Users.query.join(sub, sub.c.name == Users.name).
order_by(sub.c.fn.asc()).paginate(page, MONKEYS_PAGE, False)
您忘记通过将friend.name.label('fn')添加到组中
join(friend, Users.is_bestfriend).group_by(Users.name).group_by('fn').subquery()