1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Django・DRF】model取得時の外部結合方法

Posted at

前置き

今回は外部結合方法がメインのため、モデルの定義などは省略する。

内部結合(INNER JOIN)

以下のようなコードがある

@extend_schema(responses=SongListSerializer, tags=["song"])
class SongListView(views.APIView):
    def get(self: Self, request: Request, *args: Any, **kwargs: Any) -> Response:
        """曲一覧情報の取得"""
        songs = Song.objects.alive().select_related("artist", "album").all()

        print(songs.query)
        serializer = SongListSerializer(data=songs, many=True)
        serializer.is_valid()
        return Response(serializer.data, status=status.HTTP_200_OK)

この場合に発行されるクエリは以下の通りになる

SELECT 
  --カラム省略
FROM
 "songs"
INNER JOIN "artists"
 ON ("songs"."artist_id" = "artists"."id") 
INNER JOIN "albums" 
 ON ("songs"."album_id" = "albums"."id")
WHERE
  "songs"."deleted_at" IS NULL

そうINNER JOINとなるのである。

外部結合(LEFT JOIN)

以下のコードにすることで外部結合が行える。

# 変更前
- songs = Song.objects.alive().select_related("artist", "album").all()
# 変更後
+ songs = Song.objects.alive().select_related("album").prefetch_related("artist").all()

prefetch_relatedを利用すると中で定義したテーブルは外部結合される。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?