I ran into trouble overriding django’s ModelAdmin ChangeList Ordering.
Overriding the ModelAdmin.queryset did not help because while the Queryset can be defined, the ordering is overridden by `ChangeList.get_ordering`
My solution is to override the ModelAdmin get_changelist method and return a subclassed ChangeList.
class AccountAdmin(admin.ModelAdmin):
# ...
def get_changelist(self, request, **kwargs):
"""
Returns the ChangeList class for use on the changelist page.
Force get_ordering to return None (if no ordering specified)
to prevent from applying ordering.
"""
from django.contrib.admin.views.main import ChangeList
class SortedChangeList(ChangeList):
def get_query_set(self, *args, **kwargs):
qs = super(SortedChangeList, self).get_query_set(*args, **kwargs)
return qs.annotate(amt=Sum('entry__amount')).order_by('-amt')
if request.GET.get('o'):
return ChangeList
return SortedChangeList
We take advantage of the fact that get_changelist can be overridden, and the fact that get_query_set is called AFTER ordering is done on the ChangeList.
Let me know if you have other solutions!
