Django admin change list view disable sorting for some fields

1.4k views Asked by At

Is there are way(s) to disable the sorting function for some fields in django admin change list so for those fields, users cannot click the column header to sort the list.

I tried on the following method, but it doesn't work.

https://djangosnippets.org/snippets/2580/

I also tired to override the changelist_view in ModelAdmin but also nothing happen.

def changelist_view(self, request, extra_context=None):
    self.ordering_fields = ['id']
    return super(MyModelAdmin, self).changelist_view(request, extra_context)

In the above case, I would like to only allow user to sort the list by ID.

Anyone has suggestion? Thanks.

1

There are 1 answers

1
Mp0int On BEST ANSWER

For Django 1.7 (or the version that I last use) do not support such things. One possible dirty work-around could be defining a model class method and using that method instead of model field.

class TestClass(Model):
    some_field = (.....)
    other_field = (........)

    def show_other_field(self):
        return self.other_field

class TestClassAdmin(ModelAdmin):
     list_display = ("some_field", "show_other_field")

Since show_other_field is a model class method, django do not knows how to sort (or process) the return result of that method.

But as I said, this is a dirty hack that might require more processing (and maybe more database calls) according to use-case than displaying a field of a model.

Extra: If you want to make a model method sortable, you must pass admin_order_field value like:

def show_other_field(self):
    return self.other_field
show_other_field.admin_order_field = "other_field"

That will make your model method sortable in admin list_display. But you have to pass a field or relation that is usable in the order_by method of database api.

TestClass.objects.filter(....).order_by(<admin_order_field>)