FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 3탄 데이터 가져오기(Read, SELECT문)
SQLAlchemy로 데이터 가져오기
공식문서를 보니 SQL 알케미를 이용해서 데이터를 가지고 오는 방법이 정말 여러가지가 있었습니다.
1.x 방식과 2.0방식 두가지가 있는데 주로 인테넷에서는 1.x 스타일로 설명 된것이 많아 저는 2.0방식을 소개해보도록 하겠습니다.
공식문서의 1.x 스타일과 2.0 스타일 비교
https://docs.sqlalchemy.org/en/14/changelog/migration_20.html#migration-orm-usage
기본적인 SELECT 문 사용법
예제용 테이블 생성
id | age | |
1 | aa | 1 |
2 | bb | 2 |
3 | cc | 3 |
4 | dd | 4 |
1. scalars(select 문) 방식
from sqlalchemy import select
results = db.scalars(select(User)) ## return ScalarResult
for result in results:
print(f"id: {result.id} email: {result.email}")
# 출력 결과
id: 1 email: aa
id: 2 email: bb
id: 3 email: cc
id: 4 email: dd
- db.scalars(select(User)) 이것의 리턴값은 ScalarResult가 나오는데 .fist()나 .all()을 사용하면 User 인스턴스가 나옵니다.
- .all()은 [User, User, … User] 와 같은 리스트 형태로 리턴되고 .fist() 단독으로 User인스턴스가 나옵니다.
- 개인적으로는 ScalarResult 를 바로 쓰는것 보다는 all이나 first를 사용하는것이 자료형 확인도 가능하기 때문에 좋을거 같습니다.
2. execute(select 문) 방식
- execute문을 이용해서도 같은 결과를 얻을수 있습니다.
res = db.execute(select(User)).scalars().all()
for result in res:
print(f"id: {result.id} email: {result.email}")
# 출력 결과
id: 1 email: aa
id: 2 email: bb
id: 3 email: cc
id: 4 email: dd
- db.execute(select(User)).scalars() == db.scalars(select(User)) 같은 결과가 나옵니다.
- 이번에는 뒤에 .all() 을 써서 [User, User, … User] 같은 리스트 형태로 바꾸어 출력했습니다.
3. select_from 사용법
stmt = select(User).select_from(User)
res = db.execute(stmt).scalars().all()
for re in res:
print(re.email, re.age)
print(res)
# 출력결과
aa 1
bb 2
cc 3
dd 4
[<__main__.User object at 0x000001B588565EE0>,
<__main__.User object at 0x000001B588565AF0>,
<__main__.User object at 0x000001B588565DF0>,
<__main__.User object at 0x000001B588565940>]
- select_from은 주로 JOIN문을 사용할때 사용합니다.
4. 특정 컬럼만 가지고 오기
일반적인 셀렉트문과 같이 특정 컬럼을 가지고 오는것도 가능합니다.
stmt = select(User.__table__.c.email,User.__table__.c.age).select_from(User)
res = db.execute(stmt).scalars().all()
print(res)
# ['aa', 'bb', 'cc', 'dd']
stmt = select(User.__table__.c.email,User.__table__.c.age).select_from(User)
res1 = db.execute(stmt).all()
print(db.execute(stmt))
## [('aa', 1), ('bb', 2), ('cc', 3), ('dd', 4)]
- 이전에 User(Base)로 생성한 인스턴스는 .__table__ 을 통해 테이블 자료형으로 변환이 되고 이 테이블 자료형에 .c.컬럼명 으로 select문에 컬럼을 입력할수 있습니다.
- db.execute(stmt).scalars().all() db.execute(stmt).all() 도 차이가 있는데 scalars().all() 을 쓰면 앞에 있는 컬럼들만 리스트 형태로 반환되고 ['aa', 'bb', 'cc', 'dd']
- 쓰지않으면 각각의 컬럼의 데이터들이 이렇게 반환 됩니다. [('aa', 1), ('bb', 2), ('cc', 3), ('dd', 4)]
아마 그래서 특절 컬럼만 SELECT할때는 아래와 같은 형태로 쓸거 같습니다.
stmt = select(User.__table__.c.email,User.__table__.c.age).select_from(User)
res1 = db.execute(stmt).all()
필터링 하는 법
필터링하는 법은 filter, where를 사용하는 법 둘다 있습니다. 세부적으로는 차이가 있을수 있겠지만 결과는 똑같이 나오니 편한것으로 쓰면 좋을거 같습니다.
1. scalars(select) 방식
results = db.scalars(select(User).where(User.email=="aa")).first()
print(results.email,results.age)
# 출력 결과
aa 1
- where로 되있는곳에 filter를 사용해도 같은 결과가 나옵니다.
2. execute를 사용하는 법
filtered_user = db.execute(select(User).where(User.email=="aa")).scalars().first()
print(filtered_user.email,filtered_user.age)
# 출력 결과
aa 1
이렇게 간단하게 SELECT문 사용법을 알아보았습니다. JOIN하는법 등 공부해야 할것들이 많지만 이정도만 알아도 간단한 프로젝트를 진행하는데는 무리가 없을거 같습니다. 이번에 새로 공식문서를 보면서 그냥 SQL문을 알케미로 사용하는 방법도 배웠습니다. 앞으로 더 공부하여 SQL알케미에 관한 내용 종종 업데이트 하도록 하겠습니다.
SQLALCHEMY 관련 포스팅 링크
2022.07.04 - FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 1탄 초기설정, 데이터 입력하기
2022.07.05 - FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 2탄 삭제, 수정
2022.07.05 - SQLAlchemy로 이미 있는 데이터베이스(테이블) 사용하기
2021.11.06 - [SQL] Postgres에서 중복도 제거하고 다른 컬럼 기준으로 정렬하기(DISTINCT, ORDER BY, subquery
2021.08.16 - SQLALCHEMY를 이용한 PostgreSQL 사용법
도움 받은 사이트
https://soogoonsoogoonpythonists.github.io/sqlalchemy-for-pythonist/tutorial/
'프로그래밍사업 > 사이드 프로젝트' 카테고리의 다른 글
[git,ssh] 맥북에서 ssh를 이용해서 깃허브 계정 여러개 사용하기 (0) | 2022.07.24 |
---|---|
[SQLALchemy, python,MySQL] date, time, DateTime 자료형 입력하고 불러오기(타임존 적용까지) (0) | 2022.07.17 |
FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 2탄 삭제, 수정 (0) | 2022.07.05 |
SQLAlchemy로 이미 있는 데이터베이스(기존 테이블) 사용하기 (0) | 2022.07.05 |
FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 1탄 초기설정, 데이터 입력하기 (0) | 2022.07.04 |
댓글