[SQLAlchemy] SQLAlchemy 로딩 전략

minsu·2025년 1월 7일

joinedload: 관계된 객체를 즉시 로드하기 위해 sql join을 사용

# 부모 객체와 자식 객체를 함께 즉시 로드해야할 때 사용
from sqlalchemy.orm import joinedload
query = session.query(Parent).options(joinedload(Parent.children))

subqueryload: 관계된 객체를 서브쿼리로 로드

# 부모 객체를 먼저 로드하고, 그 후 서브쿼리를 사용하여 자식 객체를 로드할 때 적합
from sqlalchemy.orm import subqueryload
query = session.query(Parent).options(subqueryload(Parent.children))

selectinload: 관계된 객체를 별도의 select 문으로 로드

# 부모 객체가 여러개 있고 각 부모 객체에 대한 자식 객체를 한번의 쿼리로 로드할 때 유용
from sqlalchemy.orm import selectinload
query = session.query(Parent).options(selectinload(Parent.children))

lazyload: 객체가 실제로 액세스될 때까지 로드하지 않음

# 즉시 로딩이 필요하지 않고, 실제로 객체가 사용될 때 로드해도 문제가 없을 때 적합
# 특정 객체의 자식 객체를 사용하지 않을 가능성이 높을 때
from sqlalchemy.orm import lazyload
query = session.query(Parent).options(lazyload(Parent.children))

immediateload: 객체를 즉시 로드

# 특정 객체가 반드시 필요하며, 가능한 빨리 로드해야 할 때 사용
from sqlalchemy.orm import immediateload
query = session.query(Parent).options(immediateload(Parent.children))

noload: 관계된 객체를 전혀 로드하지 않음

# 특정 객체의 관련 데이터를 전혀 사용하지 않을 때
from sqlalchemy.orm import noload
query = session.query(Parent).options(noload(Parent.children))

raiseload: 관계된 객체를 로드하려고 할 때 예외를 발생 시킴

# 관계된 객체를 로드하지 않고자 할 때 이를 확실히 하기 위해 사용, 디버깅에 유용
from sqlalchemy.orm import raiseload
query = session.query(Parent).options(raiseload(Parent.children))

contains_eager: 이미 로드된 관계를 사용하여 eager loading을 수행

# 직접 작성한 쿼리에서 이미 로드된 데이터를 사용하고자 할 때 사용
from sqlalchemy.orm import contains_eager
query = session.query(Parent).join(Parent.children).options(contains_eager(Parent.children))

load_only: 특정 컬럼만 로드하여 필요한 데이터만 가져오도록 최적화

# 필요한 컬럼만 로드하여 쿼리 성능을 최적화하고자 할 때 사용
from sqlalchemy.orm import load_only
query = session.query(Parent).options(load_only(Parent.name, Parent.age))

defer: 특정 컬럼의 로딩을 지연 시킴

# 특정 컬럼을 나중에 필요할 때까지 로드하지 않고 지연시키고자 할 때 사용
from sqlalchemy.orm import defer
query = session.query(Parent).options(defer(Parent.large_blob_column))

undefer: 지연 로딩된 컬럼을 즉시 로드

# 지연 로딩된 컬럼을 즉시 로드해야 할 때 사용
from sqlalchemy.orm import undefer
query = session.query(Parent).options(undefer(Parent.large_blob_column))

with_parent: 부모 객체를 기준으로 관련된 객체를 로드

# 부모 객체를 기준으로 자식 객체를 로드하고자 할 때 사용
from sqlalchemy.orm import with_parent
query = session.query(Child).with_parent(parent_instance, "children")

defaultload: 기본 로딩 전략을 적용, 이를 사용하여 중첩된 관계의 로딩 전략을 지정할 수 있음

# 중첩된 관계의 로딩 전략을 지정하고자 할 때 사용
from sqlalchemy.orm import defaultload
query = session.query(Parent).options(defaultload(Parent.children).joinedload(Child.toys))

aliased: 쿼리에서 사용되는 엔티티에 대해 별칭을 정의

# 복잡한 쿼리에서 엔티티의 별칭을 사용하고자 할 때, 동일한 테이블을 여러 번 조인해야 할 때
from sqlalchemy.orm import aliased
ParentAlias = aliased(Parent)
query = session.query(Parent).join(ParentAlias, Parent.children).filter(ParentAlias.name == "John")
profile
3년차 백엔드 개발자

0개의 댓글