[Django]-Sort order of Django Admin records

183👍

class SeminarInline(admin.StackedInline):
    model = Seminar
    extra = 0
    ordering = ('-date',)

worked for me (above adapted from my model)
It sorted in descending date order

👤pbmuk

25👍

There is also the possibility to override get_ordering(self, request) of the ModelAdmin which allows for case insensitive ordering:

from django.db.models.functions import Lower

class MyModelAdmin(ModelAdmin):
    list_display = ('name',)
    search_fields = ['name']

    def get_ordering(self, request):
        return [Lower('name')]  # sort case insensitive

24👍

You can add Meta options to a Django model which can dictate how it behaves. There is an ordering option which defines by which model attribute records should be ordered.

You can find the documentation for the meta ordering option here in the Django docs:

23👍

Below is the method as per 4.0 documentation

# mymodel/admin.py

from django.contrib import admin
from . import models

# admin.site.register(models.MyModel)

@admin.register(models.MyModel)
class MyModelAdmin(admin.ModelAdmin):
    ordering = ['-last_name']

Here last_name is the field inside MyModel.

9👍

For example if you want the table to be sorted by percentage :

  1. Go to models.py file in your mainapp
  2. class Meta:
     abstract = True
     ordering = ['-percentage'] #Sort in desc order
    
  3. class Meta:
     abstract = True
     ordering = ['percentage'] #Sort in asc order
    

7👍

If you want to define a order within an InlineAdmin django doesn’t offer you a a generic solution to do this! There are some snippets out there that enable you to add this functionality to the admin, also the grappelli skin offers you such a feature!

0👍

Yes, you can add ordering to your ModelAdmin. This is separated from your models.py ordering.

Leave a comment