Django admin sortable custom fields

833 views Asked by At
class EventAdmin(admin.ModelAdmin)
    list_display = (..., 'ticket_value')

    def ticket_value(self, inst):
        return normalize(self.value)

I need to sort Event objects by my custom column "ticket_value" in Django admin panel. There are many exampels with queryset, annotate, aggregate but I need to apply normalize function for each ticket value.

How can I make ticket_value column sortable in Django admin?

1

There are 1 answers

0
AdamKG On

You don't. The admin screen relies on QuerySet.order_by(); it can only do the ordering that can be represented in an ORDER BY clause. Relevant source:

https://github.com/django/django/blob/a89c856a7aadc830951342a1fa49c1a1b5ac9156/django/contrib/admin/views/main.py#L387

Consider what would happen with large datasets - in order to have the pagination be consistent, the admin would have to evaluate your normalization function for every row in the database, for every request.