Kinsa | Pixels + Logic Blog

Adding a Sortable Column to a Models List View in the Django Admin

To create a sortable column that is based on a method in the Django admin change list, utilize the attribute admin_order_field and set it to a dunder delineated database traversal of an attribute to sort on:

def get_accepted(self, obj):
    return obj.accepted

# utilize the Admin's checkbox icon to indicate True as a visual indica
get_accepted.boolean = True
# sort by "obj.accepted"
get_accepted.admin_order_field = 'accepted'

...

list_display = [..., 'get_accepted', ...]

A more complicated, and slightly more complete example:

from django.contrib import admin
from django.urls import reverse 
from django.utils.html import format_html

class MyModelAdmin(admin.ModelAdmin):
    def get_project(self, obj):
        if obj.project:
            url = reverse('admin:myapp_project_change', args=[obj.project.id])
            return format_html(f'{obj.project.name}')
        return '-'

    # sort by "obj.project.name"
    get_project.admin_order_field = 'project__name'

    ...

    list_display = [..., 'get_project', ...]

The Django documentation mentions this functionality in passing as "custom display functions".

Feedback?

Email us at enquiries@kinsa.cc.

Found this useful?

We always appreciate a pint!