How do I order by multiple fields in the django-admin?
Thanks
Try this:
Set ordering in your model Meta
:
class Meta:
ordering = ["some_field", "other_field"]
and add this class in admin.py
:
from django.contrib.admin.views.main import ChangeList
class SpecialOrderingChangeList(ChangeList):
"""
Django 1.3 ordering problem workaround
from 1.4 it's enough to use `ordering` variable
"""
def get_query_set(self):
queryset = super(SpecialOrderingChangeList, self).get_query_set()
return queryset.order_by(*self.model._meta.ordering)
Add this method in your admin.ModelAdmin
def get_changelist(self, request, **kwargs):
return SpecialOrderingChangeList
source: https://groups.google.com/forum/?fromgroups#!topic/django-users/PvjClVVgD-s
until django 1.4 (currently in alpha) the django admin only orders by the first column in Meta ordering
. You can work around this by overriding the queryset:
class MyAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(MyAdmin, self).queryset(request)
qs = qs.order_by('last_name', 'first_name')
return qs
Further to user535010's response above: I struggled because after adding the suggested code I was no longer able to order the fields by clicking on the headings in the admin list view. I modified the get_changelist method suggested for MyModelAdmin as follows:
def get_changelist(self, request, **kwargs): #ordering issue in 1.3 workaround
try:
if not request.GET['o']:
return SpecialOrderingChangeList
except KeyError:
pass
return super(MyModelAdmin, self).get_changelist(request)
Django model admin supports ordering by multiple values in Django 2.0+. You can now use it like this:
class MyAdmin(admin.ModelAdmin):
ordering = ['last_name', 'first_name']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With