2014-12-17 3 views
3
처음 비어 있지 않은 이름에 대한 쿼리하고

반환 : 나는 acc_username, us_username 중 첫 번째 비어 있지 않은 값을 검색하고SQLAlchemy의 : COALESCE() 첫째하지 NULL이 아닌 빈 결과

query = session.query(
    Account.id.label('acc_id'), 
    Account.username.label('acc_username'), 
    User.username.label('us_username'), 
    User.another_username.label('also_username'), 
    User.email.label('email') 
).join(Account.user) 

을 그리고 afterwords을, also_usernameemail. 이를 위해 나는에서 KeyedTuple를 생성하는 기능을 준비했습니다 id 먼저 비어 있지 않은 문자열 값을 발견 : (

for q in query.all(): 
    account_tuple = KeyedTuple(
     [q.acc_id, q.acc_username or q.us_username or q.also_username or q.email or ''], 
     labels=_LABELS) 

을 대신 차라리 처음 비어 있지 않은 값을 반환 제외 coalesce의 형태를 사용합니다 파이썬에서 먼저 not False 값) not NULL 대신. 적절한 방법이 있습니까? 나는이 모든 논리를 질의에 맡기고 또 다른 것을 KeyedTuple을 별도의 기능으로 생성하지 않도록 고맙게 생각한다.

답변

1

내가 SQLAlchemy의에서 MySQL의 case 방법을 사용하여이 문제를 처리 한 :

query = session.query(
    Account.id.label('acc_id'), 
    case(
     [ 
      (Account.username != '', Account.username), 
      (User.username != '', User.username), 
      (User.another_username != '', User.another_username), 
      (User.email != '', User.email) 
     ], 
     else_='') 
    .label('username') 
    .join(Account.user) 

그리고이 비록

먼저 비어 있지 않은 문자열 (빈 문자열 비교도 NULL 항목을 거부를 달성하기 적절한 방법이 될 수 없습니다)이 경우에는 잘 작동하고 두 번째 KeyedTuple 생성은 생략합니다.