Django ORM Join에 대해서 질문드립니다.

조회수 2861회

디장고 orm의 join에 대해서 질문드립니다.

제가 알기로 querySet을 사용해서 join을 하려면 아래 두가지 방식이 있는걸로 압니다.

1 model = model.objects.select_related('field_name')
2 model = model.objects.prefetch_related('field_name')

2의 방법은 모든 테이블 관계에서 사용 가능하지만 1의 방법보다 sql의 실행 횟수가 많기 때문에 필요한 경우가 아니라면 select_related()를 사용한다고 들었습니다.

1의 방법은 어떤 테이블 관계에서만 사용이 가능한지 궁금합니다.

감사합니다~

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • prefetch_related() 에 설명이 잘 나와있습니다.

    This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

    select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

    prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

    한글로 대략 요약하면

    1. select_related는 SQL join문을 만들어, related object의 field를 SELECT 문에 포함하는 방식을 쓰고,
    2. prefetch_related는 각 relationship을 갖고와 python에서 joining 하는 방식을 씁니다.

    아무래도 SQL문을 바로 실행하는 쪽(1번)이 언어에서 join을 하는 것보다(2번) 빠릅니다. 대신 select_related는 foreign-key/1:1 relation ship 에서만 쓸 수 있습니다.

    • (•́ ✖ •̀)
      알 수 없는 사용자
    • foreign-key라고 하면 1:N을 말하는건가요? 알 수 없는 사용자 2017.7.13 17:36
    • 네 Foreign Key는 1:N 관계를 말하는 게 맞습니다 이승연 2017.10.20 11:47

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)