Change: Sorting in Admin

created on Dec. 1, 2012, 1:56 p.m. by Hevok & updated on Dec. 1, 2012, 1:56 p.m. by Hevok

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.

.. sourcecode:: python

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:

.. sourcecode:: python

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

    uni_sort.admin_order_field = 'sort'
    uni_sort.short_description = _(u'name')
    ...

.. sourcecode:: python

# admin.py
...
class Admin
    list_display('uni_sort', 'parent', 'name', 'slug',)
...
300px-Metal_movable_type.jpg

Tags: django
Categories: reST
Parent: Web Framework

Comment: Created entry.

See entry | Admin

Comment on This Data Unit