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

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s