Sorting in Admin

Created on Dec. 1, 2012, 1:56 p.m. by Hevok & updated by Hevok on May 2, 2013, 5:26 p.m.

In the admin interface for a given model the __str__() or __unicode__() methods can be used as string representation, as they are valid in list_display as any other model method.

list_display = ('__unicode__', 'other_field')

Those fields are not database fields and cannot be used in sorting (because sorting is done at the database level).

However if an element in list_display represents a certain database field, it can be used by indicating it via setting the admin_order_field attribute for this element.

In such sorting can be enabled by defining an extra method:

class Model(models.Model):
    def uni_sort(self):
        return self.__unicode__()

    uni_sort.admin_order_field = 'sort'
    uni_sort.short_description = _(u'name')
class Admin
    list_display('uni_sort', 'parent', 'name', 'slug',)

Tags: rest, django
Categories: reST
Parent: Web Framework

Update entry (Admin) | See changes

Comment on This Data Unit