【Django】文字列で好きな順番にソートする【Case, When】

from django.db.models import Case, When, Value, IntegerField
from .models import YourModel

# ソート順を定義
sort_order = Case(
    When(status='public', then=Value(1)),
    When(status='private', then=Value(2)),
    When(status='delete', then=Value(3)),
    default=Value(4),
    output_field=IntegerField()
)

# クエリセットを注釈付けしてソート
queryset = YourModel.objects.annotate(sort_order=sort_order).order_by('sort_order')
Djangoで特定のアイテムを優先してソートする Djangoで特定のアイテムを優先してソートする

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です