Django admin sort order

DjangoDjango Models

Django Problem Overview


i have went through the Poll tutorial on http://docs.djangoproject.com.

I would like to know if it is possible to add a sort order to the 'Choice' Model when editing a Poll and how would i accomplish that

thanks

Django Solutions


Solution 1 - Django

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

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

Solution 2 - Django

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:

Solution 3 - Django

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

Solution 4 - Django

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!

Solution 5 - Django

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
    

Solution 6 - Django

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.

Solution 7 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLyloView Question on Stackoverflow
Solution 1 - DjangopbmukView Answer on Stackoverflow
Solution 2 - DjangoMarcus WhybrowView Answer on Stackoverflow
Solution 3 - DjangoRisadinhaView Answer on Stackoverflow
Solution 4 - DjangoBernhard VallantView Answer on Stackoverflow
Solution 5 - Djangosauravjoshi23View Answer on Stackoverflow
Solution 6 - DjangoShashi RanjanView Answer on Stackoverflow
Solution 7 - DjangoBenny ChanView Answer on Stackoverflow