Devlog

[SQLAlchemy] - first(), scalar(), one() 본문

Database/SQLAlchemy

[SQLAlchemy] - first(), scalar(), one()

recoma 2022. 4. 22. 17:01
728x90

최근에 FastAPI/Flutter 기반의 토이 프로젝트를 진행하면서 SQLAlchemy라는 것을 공부하면서 사용하고 있습니다. sqlalchemy에서 데이터를 하나만 갖고오는 함수가 first(), one(), scalar() 이 세가지나 있는 데, 왜 굳이 하나만 갖고오는 함수가 세개 씩이나 있는 지 처음에는 이해를 할 수가 없었지만, reference를 참고하고 나니 각자의 기능 차이가 있었습니다.

 

Query API — SQLAlchemy 1.4 Documentation

Query API This section presents the API reference for the ORM Query object. For a walkthrough of how to use this object, see Object Relational Tutorial (1.x API). The Query Object Query is produced in terms of a given Session, using the Session.query() met

docs.sqlalchemy.org

 

first()

Return the first result of this Query or None if the result doesn’t contain any row.
first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).

SQL문에서의 limit 1과 같은 기능을 합니다. 실제로 sql문으로 넘어갈 때 limit 1 구문을 사용해서 하나의 데이터를 출력합니다. 만약 만족하는 데이터가 없다면 None을 출력합니다. 단 Join을 이용한 테이블에서 first()를 호출할 때, 해당 테이블의 상태에 따라 여러 개의 행으로 출력될 수 있습니다만, 아직 Join을 이용한 orm 구문을 사용해 본 적이 없기 때문에 어떻게 되는 지는 잘 모르겠군요, 혹시 Join하고 first()를 동시해 사용하는 상황이 올 때 추가적으로 작성하겠습니다. 사실 join 쓰려고 발버둥 치긴 하는데 자꾸 안되서 그냥 테이블을 합성하는 정도로만 사용하고 있어요 ㅠㅠ

 

scalar()

Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound.

first() 하고 기능이 비슷합니다. 마찬가지로 데이터가 있으면 출력하고 없으면 None을 리턴합니다. 그러나 해당 쿼리문에 대한 행이 여러개 있으면 MultipleResultsFound를 호출한다는 차이가 있습니다.

 

one()

Return exactly one result or raise an exception.
Raises sqlalchemy.orm.exc.NoResultFound if the query selects no rows. Raises sqlalchemy.orm.exc.MultipleResultsFound if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

scalar() 처럼 행이 여러개 있으면 MultipleResults를 호출할 뿐만 아니라, 데이터가 없어도 NoResultFound라는 예외를 호출합니다.

 

요약

함수명 목적 행이 없는 경우 행이 여러개 있는 경우
first() 여러 행에서 하나만 출력 None 한개만 출력
scalar() 하나만 출력 None MultipleResultFound 호출
one() 하나만 출력 NoResultFound 호출 MultipleResultFound 호출

first()는 여러 행에서 가장 우선순위가 큰 데이터, 즉 예를 들어 점수가 가장 높다거나 순위가 가장 높은 데이터를 출력할 할 때 사용하고, scalar()와 one()은 반드시 데이터가 하나만 존재해야 하고, 여러 데이터가 있을 경우에 대한 대처가 필요할 때 사용하면 유용할 것 같습니다. 저는 개인적으로 scalar()와 one() 중에 클린 코드를 고려해서 scalar()를 주로 사용하는 편입니다.

728x90
반응형