django admin排序外键字段列表 [英] django admin sort foreign key field list

查看:391
本文介绍了django admin排序外键字段列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django管理视图中是否有一个选项来排序外键字段?即我有一个外键为学校模式,它显示为一个下拉列表,按照pk排序 - 我希望按字母顺序排序。

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 would like it to be sorted alphabetically.

推荐答案

当然可以...

  • 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具体方法(其他方法在我的回答中链接到上面)

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)

其他3个非管理员特定方法的示例我的帖子链接在上面。

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

这篇关于django admin排序外键字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆