본문 바로가기
SQLAlchemy

2.0 요약 정리

by 스티브 십잡스 2024. 2. 19.
  1. session.query() 방식에서 session.execute()
    • execute()의 리턴 타입은 Result object.
      • Result object
        • Named tuple과 유사한 인터페이스를 가진 Row object를 반환하는 Iterable function.
  2. Result object에 대해서 Iterating 없이 결과를 얻을 수 있는 방법
    • all()
      • to return a list with a row object for each result row.
      • 예) [row(값1, 값2, ...), row(값1, 값2, ...) , ...]
        • SQL 또는 ORM에서 프로젝션을 하는 경우, 용이하다.
        • for loop를 돌면서 select하는 컬럼의 별칭이나, 객체의 속성을 매핑하여 값을 확인할 수 있다.
    • first()
      • to return the first result row.
      • 예) 여러 개의 Row object가 조회되면, 첫 번째 Row object를 리턴한다.
    • one()
      • to return the first result row, and raise an exception if there are no results or more than one result.
        • 1개 이상의 Row object가 조회되면, MultipleResultsFound
        • Row object가 조회되지 않으면, NotResultFound
    • one_or_none()
      • to return the first result row, None if there are no results, or raise an exception if there are more than one result.
        • 1개 이상 조회되면, MultipleResultsFound
        • 조회되지 않으면, None
  3. Row object는 Named tuple과 유사하다.
    • 리턴 값을 출력해보면,
      • Row object에 값이 하나인 경우에는 (값, )
        • Row object가 하나의 값을 가질 때, tuple에서 값을 추출하는 것은 매우 비효율적이다.
      • Row object가 여러 개의 값을 가지는 경우에는 (값, 값, ...)
  4. Row object가 하나의 값을 가질 때, tuple에서 값을 추출하는 방법
    • scalars()
      • returns a ScalarResult object with the first value of each result row. The methods of Result listed above are alse available on this new result object.
        • ScalarResult object를 iterating하면, 값1을 확인할 수 있다. (아래 내용 참고)
      • all()과 함께 사용하여 리스트 형태를 리턴한다.
        • session.execute("statement").scalars().all()
        • [row1(값1, ), row2(값1, ), ...] 인 경우, [값1, 값1, ...]이 리턴된다.
          • ORM에서 엔티티를 조회할 때, 용이하다.
    • scalar()
      • return the first  value of the first result row.
      • 1.4 방식이며, 2.0에서 권장하지 않는 방법이다.
        • scalar_one(), scalar_one_or_none() 사용을 권장한다.

[참고 글]

 

What's New in SQLAlchemy 2.0?

You may have heard that a major version of SQLAlchemy, version 2.0, has been released in January 2023. Or maybe you missed the announcement and this is news to you. Either way, I thought you'd be…

blog.miguelgrinberg.com

 

'SQLAlchemy' 카테고리의 다른 글

SpringDataJPA 일부 구현해보기  (0) 2024.05.05
DTO, 객체 인스턴스 생성  (0) 2024.03.26