我有一个带有postgresql的烧瓶应用程序,我想根据他们最好的朋友名称对用户进行排序。为了解释数据库,它在bestfriend中有一对一的关系,我使用flask-migrate和Alembic.But得到了这个错误,但是如果你能告诉我如何解决它,问题出在哪里?
错误
sqlalchemy.exc.ProgrammingError
ProgrammingError :( ProgrammingError)列" users_1.name"必须出现 在GROUP BY子句中或在聚合函数LINE 2中使用: FROM users JOIN(SELECT users.name AS name,users_1.name AS
... ^' SELECT 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名称,users_1.name AS fn \ nFROM用户JOIN用户AS users_1 ON users_1.id = users.bestfriend_id GROUP BY users.name)AS anon_1 ON anon_1.name = users.name ORDER BY anon_1.fn ASC \ n LIMIT %(param_1)s OFFSET%(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)
答案 0 :(得分:0)
您忘了通过
将friend.name.label('fn')添加到群组中join(friend, Users.is_bestfriend).group_by(Users.name).group_by('fn').subquery()