0
1

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 1 year has passed since last update.

[Django Rest Framework] OrderingFilterを使ってソート機能を実装しよう!

Posted at

概要

Django Rest Frameworkを使って一覧のAPIにソート機能を実装する方法について解説します

前提

  • Djangoのプロジェクトを作成済み

OrderingFilter

Django Rest Frameworkを使ってソート機能を実装する際はOrderingFilterを使うのが一般的です
以下のようにfilter_backendsにOrderingFilterを指定することで実装できます

from rest_framework.viewsets import ModelViewSet

from application.models import Product
from application.serializers.product import ProductSerializer
from rest_framework.filters import OrderingFilter


class ProductViewSet(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [OrderingFilter]

実装したAPIを確認します

スクリーンショット 2023-11-12 13.18.59.png

Filterの箇所を押すと以下のように適用したいソート条件を入力できます
スクリーンショット 2023-11-12 13.19.25.png

ソートしてみよう

試しにPrice - 昇順を押すと以下のように昇順に値段がソートされます
その際は

?ordering=price

というふうにソートパラメータがAPIのパスの後ろに適用されます

スクリーンショット 2023-11-12 13.20.41.png

逆にソート順を降順にする際は

?ordering=-price

というふうにソートパラメータに-が適用されます

スクリーンショット 2023-11-12 13.22.49.png

デフォルトのソート

また、ordering_fieldsにパラメータを設定するとデフォルトのソート順を指定できます
以下のように設定すればpriceのソートパラメータなしで値段の昇順にソートされます
ただし、一般的にバックエンド側ではなく、フロントエンド側でデフォルトのソート順を保持しておいてフロントエンドから送られたソートパラメータに従ってソートするケースが多いので参考程度に認識していただければと思います

class ProductViewSet(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [OrderingFilter]
    ordering_fields = "price"

スクリーンショット 2023-11-12 13.27.27.png

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?