Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-admin order by multiple fields

How do I order by multiple fields in the django-admin?

Thanks

like image 494
Imran Azad Avatar asked Jan 13 '12 18:01

Imran Azad


4 Answers

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

like image 133
user535010 Avatar answered Nov 02 '22 06:11

user535010


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 
like image 44
second Avatar answered Nov 02 '22 07:11

second


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)
like image 1
jenniwren Avatar answered Nov 02 '22 08:11

jenniwren


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']
like image 1
niekas Avatar answered Nov 02 '22 06:11

niekas