[Django]-Django admin sort foreign key field list

79👍

✅

ModelAdmin specific ordering via formfield_for_foreignkey:

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

Examples for 3 other non-admin-specific methods:

8👍

It seems to work to add an admin class to the model admin, with the ordering equal to the field you want the drop down list sorted by.

# in the admin.py file

class SchoolAdmin(admin.ModelAdmin):
    ordering = ['school_name']

admin.site.register(SchoolModel, SchoolAdmin)

This works if you are willing to have an edit/add option next to drop down list.

3👍

The approved answer might override other changes on the queryset, so I prefer to use this because it’s safer:

class StudentAdmin(admin.ModelAdmin):
    def get_field_queryset(self, db, db_field, request):
        queryset = super().get_field_queryset(db, db_field, request)
        if db_field.name == 'school':
            queryset = queryset.order_by('name')
        return queryset

3👍

You can override formfield_for_foreignkey() to change order as shown below:

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == "school":            
            formfield.queryset = School.objects.order_by('name')
        return formfield

Leave a comment