Django – Sort the Djano Admin list table by specific field

We could display our model objects on the Django Admin.

 

The list table could be sorted by specific column. Say we have added the creation date to the Person model class.

models.py

from django.db import models

class Person(models.Model):
  name       = models.CharField(max_length=256)
  homepage   = models.URLField(max_length=256)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

  def __unicode__(self):
    return self.name

 

In the admin.py, we could add the sorting by setting the ordering attribute.

admin.py

from django.contrib import admin
from eureka.models import Person

class PersonAdmin(admin.ModelAdmin):  
  list_display = ('name', 'view_homepage_link', 'created_at', 'updated_at')
  ordering = ('-created_at',) # The negative sign indicate descendent order

  def view_homepage_link(self, obj):
    return '<a href="%s" target="_blank">%s</a>' % (obj.homepage, obj.homepage,)
  view_homepage_link.allow_tags = True
  view_homepage_link.short_description = 'Homepage' # Optional

admin.site.register(Person, PersonAdmin)

 

Check it out.
django-admin-sorting

Done =)

Reference: StackOverflow – Ordering the display items alphabetically in Django-Admin

2 thoughts on “Django – Sort the Djano Admin list table by specific field”

Leave a reply to ykyuen Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.