python – Show alphabetically sorted objects in Django admin

Question:

In my Django project I have created an app called Deportes (added in the settings.py ). When entering the Django administrator in the Sports area, the added sports are listed. I would like this list to be shown in alphabetical order.

The code I use inside models.py is very simple:

def __unicode__(self): 
    return self.nombre_deporte_es

Answer:

One option is, if you want the order to apply at the system level and for all cases, you have to define this order in the Meta of your model, specifically the ordering option:

# models.py

class Deportes(models.Model):
    # Tus columnas

    def __unicode__(self): 
        return self.nombre_deporte_es

    class Meta:
        ordering = ['nombre_deporte_es']

The above form would apply to ascending order by name. For descending order you can use:

# models.py

class Deportes(models.Model):
    # Tus columnas

    def __unicode__(self): 
        return self.nombre_deporte_es

    class Meta:
        ordering = ['-nombre_deporte_es'] # Nota el guión

If it is not the case that you want this order to apply at the system-wide level and you only want it to apply for your admin, you would have to make some changes in your admin.py and edit the get_queryset function:

# admin.py
from django.contrib import admin
from tuapp.models import Deportes

class DeportesAdmin(admin.ModelAdmin):  
    def get_queryset(self, request):
        queryset = Deportes.objects.all().order_by('nombre_deporte_es')
        return queryset


admin.site.register(Deportes, DeportesAdmin)
Scroll to Top