본문 바로가기

FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 3탄 데이터 가져오기(Read, SELECT문)

ironwhale 2022. 7. 7.

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

 

Migrating to SQLAlchemy 2.0 — SQLAlchemy 1.4 Documentation

Previous: What’s New in SQLAlchemy 1.4? Next: 1.4 Changelog Up: Home On this page: Migrating to SQLAlchemy 2.0 Overview 2.0 Migration - Core Connection / Transaction 2.0 Migration - Core Usage 2.0 Migration - ORM Configuration 2.0 Migration - ORM Usage 2

docs.sqlalchemy.org


기본적인 SELECT 문 사용법

예제용 테이블 생성

id email 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탄 초기설정, 데이터 입력하기

 

FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 1탄 초기설정, 데이터 입력하기

다시 정리하는 SQL 알케미 본 내용은 https://fastapi.tiangolo.com/ko/tutorial/sql-databases/ 해당 링크의 설명과 공식문서를 참조하였습니다. 이전에 2021.08.16 - SQLALCHEMY를 이용한 PostgreSQL 사용법 을..

jh-industry.tistory.com

2022.07.05 - FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 2탄 삭제, 수정

 

FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 - 2탄 삭제, 수정

SQLAlchemy로 삭제하는 법과 수정하는 법 FASTAPI 사용을 위한 SQLAlchemy(ORM) 기초 1탄에 이어 이번에는 SQL 알케미로 삭제하는법과 수정하는 법을 정리해보 겠습니다. 삭제하기(DELETE) 삭제하기는 간단합

jh-industry.tistory.com

2022.07.05 - SQLAlchemy로 이미 있는 데이터베이스(테이블) 사용하기

 

SQLAlchemy로 이미 있는 데이터베이스(테이블) 사용하기

SQLAlchemy로 이미 있는 MySQL 의 테이블 사용하기 python으로 MySQL이나 SQLite, Postgres를 사용하기위해 SQL 알케미를 다시 공부하고 있습니다. 그러던 중 dbeaver를 이용해 이미 만든 테이블을 sql알케미로

jh-industry.tistory.com

2021.11.06 - [SQL] Postgres에서 중복도 제거하고 다른 컬럼 기준으로 정렬하기(DISTINCT, ORDER BY, subquery

 

[SQL] Postgres에서 중복도 제거하고 다른 컬럼 기준으로 정렬하기(DISTINCT, ORDER BY, subquery

SQL(Postgres)로 해보기 //Postgres SELECT * FROM ( SELECT DISTINCT ON (중복을 제거할 컬럼명) * FROM 테이블명 WHERE name='a') as foo ORDER BY id DESC; // 정렬할 컬럼 python SQLAlchemy로 해보기 from sq..

jh-industry.tistory.com

2021.08.16 - SQLALCHEMY를 이용한 PostgreSQL 사용법

 

SQLALCHEMY를 이용한 PostgreSQL 사용법

SQL 알케미랑 SQL 서버와 연결하는 부분 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker URL = "postgresql://아이디:비밀번호@서버주소/DB이름" engine = create_engine(URL,ech..

jh-industry.tistory.com


도움 받은 사이트

https://www.sqlalchemy.org/

 

SQLAlchemy - The Database Toolkit for Python

The Python SQL Toolkit and Object Relational Mapper SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides a full suite of well known enterprise-level persisten

www.sqlalchemy.org

https://soogoonsoogoonpythonists.github.io/sqlalchemy-for-pythonist/tutorial/

 

Tutorial | 파이썬 개발자를 위한 SQLAlchemy

Tutorial 이 문서는 SQLAlchemy 1.4/2.0 Tutorial (opens new window)를 번역 및 정리한 글입니다. 기존 공식 문서는 보기 어렵고, 너무 많은 내용이 담겨있습니다. 또한 초보자가 보기에 너무 어렵다는 생각이

soogoonsoogoonpythonists.github.io

 

댓글