django admin sort foreign key field list

后端 未结 3 1759
北海茫月
北海茫月 2021-01-30 17:12

Is there an option in the django admin view for ordering of foreign key fields? i.e. I have a foreign key to a \"School\" model, which shows as a dropdown, sorted on pk-- I woul

3条回答
  •  遇见更好的自我
    2021-01-30 17:25

    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
    

提交回复
热议问题