SQLAlchemy ORM LEFT OUTER JOIN with括号

时间:2016-05-27 08:18:41

标签: postgresql sqlalchemy

我正在尝试将以下原始sql转换为SQLAlchemy ORM

原始SQL:

objects = request.db.execute("select user_login.userlogin_id, user_friend.status,"\
    " user_login.email, user_info.fname, user_info.lname"\
    " from user_login "\
    " LEFT OUTER JOIN user_info on "\
    " user_info.userlogin_id = user_login.userlogin_id "\
    " LEFT OUTER JOIN user_friend on "\
    " (user_info.userlogin_id = user_friend.send_from_userlogin_id or"\
    " user_info.userlogin_id = user_friend.send_to_userlogin_id )"\
    " where email='%s' " %request.POST['q'])

SQLAlchemy版本:

objects = request.db.query(UserLogin.email, UserLogin.userlogin_id, UserInfo.fname, 
UserInfo.lname, UserFriend.status)\
.outerjoin(UserInfo, UserLogin.userlogin_id == UserInfo.userlogin_id)\
.outerjoin(UserFriend, 
or_(UserLogin.userlogin_id == UserFriend.send_from_userlogin_id \
,UserLogin.userlogin_id == UserFriend.send_to_userlogin_id) )\
.filter(UserLogin.email==request.POST['q'])

我查看了日志,以下是对我来说有点奇怪,因为它没有任何括号:

INFO  [sqlalchemy.engine.base.Engine][Dummy-4] SELECT user_login.email AS 
user_login_email, user_login.userlogin_id AS user_login_userlogin_id,
user_info.fname AS user_info_fname, user_info.lname AS user_info_lname,
user_friend.status AS user_friend_status FROM user_login LEFT OUTER JOIN 
user_info ON user_login.userlogin_id = user_info.userlogin_id LEFT OUTER JOIN 
user_friend ON 

user_login.userlogin_id = user_friend.send_from_userlogin_id OR 
user_login.userlogin_id = user_friend.send_to_userlogin_id 

WHERE user_login.email = %(email_1)s

我应该如何构建sqlalchemy,以便 user_login.userlogin_id = user_friend.send_from_userlogin_id或() user_login.userlogin_id = user_friend.send_to_userlogin_id 最后一次LEFT OUTER JOIN?

0 个答案:

没有答案