Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alphabetically order a drop-down list in Django admin?

People also ask

How do I create a drop down list in Django?

To create a dropdown in Python Django model form, we can create a char field with the choices argument set to a tuple of choices in a model class. Then we can set the model class as the model for the form. to add the color field to the MyModel model class.


You can define default ordering for Author model:

class Author(Model):
    name = CharField(max_length=100)

    class Meta:
        ordering = ('name',)

Keep in mind that this causes the objects in Django also to ordered and migration will have to be done.

You can do ordering = ['name'] under the AuthorAdmin file to order only for admin dashboard.


ModelAdmin specific ordering via formfield_for_foreignkey

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "author":
            kwargs["queryset"] = Author.objects.filter(anyfilters=anyfilters).order_by('name')
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Note IMHO its better not to set the ordering on model because the ordering of your admin page needs to be decoupled from the model.

Also all the queries fired on the model will use the order_by column, in which case you might have to index the ordering column with your other columns.


The current way to do this (January 2019):

In your admin.py file:

class AuthorAdmin(admin.ModelAdmin):
    ordering = ['name']

And then register it:

admin.site.register(Author, AuthorAdmin)

As described in the docs: https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.ordering