django admin sort foreign key field list

Sure – you can…

  • ModelAdmin specific ordering via formfield_for_foreignkey
  • Set default global ordering via a Manager
  • Set default ordering via model meta class
  • Form specific ordering then passed to your ModelAdmin

ModelAdmin specific method: (the other methods are in my answer in the post linked to above)

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(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Examples for the other 3 non admin specific methods in my post linked above.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)