How to show all users including my friends using SQLAlchemy

扶醉桌前 提交于 2019-12-11 14:24:35

问题


I am trying to show a list of all users including my friends.

Database :

relationships table:

Users table :

Server side :

    q1 = db.session.query(User).add_columns(User.id,User.name,Relationship.status).join(
        Relationship, User.id == Relationship.user1_Id).filter(Relationship.user2_Id == id)

    q2 = db.session.query(User).add_columns(User.id,User.name,Relationship.status).join(
        Relationship, User.id == Relationship.user2_Id).filter(Relationship.user1_Id == id)

    q3 = db.session.query(User).add_columns(User.id,User.name,'null').filter(User.id != id)
    result = q1.union(q2).union(q3)

If I do union q1 and q2 only, then I will get my friends correctly. But when add the third union, then I my firends list will be duplicated. I know that union is not the best way to do that , but I am new to SQLAlchemy and I would like to know how to use "join" here.

来源:https://stackoverflow.com/questions/57021469/how-to-show-all-users-including-my-friends-using-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!