Django-admin ordering multiple fields

How to order multiple fields in django-admin?

thanks

+8
source share
5 answers

Try the following:

Set the order in the Meta model:

 class Meta: ordering = ["some_field", "other_field"] 

and add this class to admin.py :

 from django.contrib.admin.views.main import ChangeList class SpecialOrderingChangeList(ChangeList): """ Django 1.3 ordering problem workaround from 1.4 it 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 to admin.ModelAdmin

 def get_changelist(self, request, **kwargs): return SpecialOrderingChangeList 

source: https://groups.google.com/forum/?fromgroups#!topic/django-users/PvjClVVgD-s

+12
source

Prior to django 1.4 (currently in alpha), the django admin only orders the first column in Meta ordering . You can get around this by overriding the query set:

 class MyAdmin(admin.ModelAdmin): def queryset(self, request): qs = super(MyAdmin, self).queryset(request) qs = qs.order_by('last_name', 'first_name') return qs 
+3
source

In addition to user535010's answer above: I struggled because after adding the suggested code, I could no longer order the fields by clicking on the headers in the admin list view. I changed 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) 
+1
source

The function required to work on ordering clicks with the correct sorting of multiple columns is as follows:

  def get_changelist(self, request, **kwargs): try: if request.GET['o']: return super(ModelAdmin, self).get_changelist(request) except KeyError: pass return SpecialOrderingChangeList 

Another way to answer jenniwren :-)

0
source

The Django model administrator supports ordering by multiple values ​​in Django 2.0+. Now you can use it like this:

 class MyAdmin(admin.ModelAdmin): ordering = ['last_name', 'first_name'] 
0
source

All Articles