0
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 Adminの並べ替えをカスタマイズする

Last updated at Posted at 2025-02-20

概要

DjangoのAdmin機能では、データの追加や修正などを簡単に行うことができる。標準機能を利用するのは簡単であるが、カスタマイズして使うこともできる。
今回はリスト表示でのソート機能をカスタマイズする方法を記載する。例えばデータベースでは文字列型で登録しているが、並び替えは数値型で行いたいという要件を満たしたい場合である。

手順

user_codeは文字列型で登録しているが、これをソートする場合は数値型で並び替えする。

  • user_code_というfieldを追加する。(Adminではアンダースコアは表示されないので、最後にアンダースコアを追加しても見た目は変わらない)
  • get_querysetをオーバライドしてint型にcastしたものを追加する
  • user_code_のadmin_order_fieldにcastしたものを対応させる
models.py
class MUser(models.Model):
    user_code = models.CharField(primary_key=True, max_length=100)
    user_name = models.CharField(max_length=100, blank=True, null=True)
admin.py
@admin.register(MUser)
class MUserAdmin(admin.ModelAdmin):
    search_fields = (
        "user_code",
        "user_name",
    )
    list_display = (
        "user_code_",
        "user_name",
    )
    list_display_links = ("user_code_", "user_name")
    cast_user_code = Cast("user_code", output_field=IntegerField())
    ordering = (-cast_user_code,)

    def user_code_(self, obj):
        return obj.user_code

    user_code_.admin_order_field = "cast_user_code"

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = qs.annotate(cast_user_code=self.cast_user_code)
        return qs
0
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
0
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?