4、Django Admin对自定义的计算字段进行排序

通常,Django会为模型属性字段,自动添加排序功能。当你添加计算字段时,Django不知道如何执行order_by,因此它不会在该字段上添加排序功能。

如果要在计算字段上添加排序,则必须告诉Django需要排序的内容。你可以通过在在计算字段方法中设置admin_order_field属性来执行此操作 。

以OriginAdmin为例,添加以下代码

python 复制代码
hero_count.admin_order_field = '_hero_count'
villain_count.admin_order_field = '_villain_count'

完整代码如下:

python 复制代码
@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):
    list_display = ("name", "hero_count", "villain_count")

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(
            _hero_count=Count("hero", distinct=True),
            _villain_count=Count("villain", distinct=True),
        )
        return queryset
    def hero_count(self, obj):
        return obj._hero_count
    def villain_count(self, obj):
        return obj._villain_count
    hero_count.admin_order_field = '_hero_count'
    villain_count.admin_order_field = '_villain_count'

显示效果:

后,点击抬头标签,显示字段排序

相关推荐
万粉变现经纪人2 小时前
如何解决 pip install -r requirements.txt 私有索引未设为 trusted-host 导致拒绝 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
毕业设计制作和分享2 小时前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
查士丁尼·绵3 小时前
笔试-九宫格三阶积幻方
python·九宫格·三阶积幻方
l1t5 小时前
DeepSeek辅助利用搬移底层xml实现快速编辑xlsx文件的python程序
xml·开发语言·python·xlsx
大飞记Python5 小时前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django
你的人类朋友6 小时前
【Node】认识multer库
前端·javascript·后端
查士丁尼·绵7 小时前
笔试-羊狼过河
python
摸鱼的老谭7 小时前
构建Agent该选Python还是Java ?
java·python·agent
lang201509288 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端
鄃鳕8 小时前
python 字典 列表 类比c++【python】
c++·python