1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Django2.2】リレーション先の値をソートして取得

1
Posted at

リレーション先の値をsortする方法

Country -> Team -> Player
というリレーションがある場合、Team一覧を取得し、かつPlayerの並びを変更したいときがある。

そんな場合、Prefetchオブジェクトを利用すれば良い。

views.py
from django.db.models import Prefetch

    def get_queryset(self):
        queryset = Team.objects.filter(country="japan").prefetch_related(
            Prefetch(Player, queryset=Player.objects.order_by('name')))
        return queryset

prefetch_relatedの中身にPrefetchオブジェクトをセットする。

公式Doc

QuerySet API reference | Django ドキュメント | Django
https://docs.djangoproject.com/ja/2.2/ref/models/querysets/#prefetch-objects

1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?