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'

显示效果:

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

相关推荐
AI_56781 小时前
Selenium+Python可通过 元素定位→操作模拟→断言验证 三步实现Web自动化测试
服务器·人工智能·python
蒜香拿铁2 小时前
【第三章】python算数运算符
python
浮尘笔记2 小时前
Go语言临时对象池:sync.Pool的原理与使用
开发语言·后端·golang
52Hz1183 小时前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
梦梦代码精3 小时前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
weixin_462446234 小时前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
REDcker4 小时前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
毕设源码-钟学长4 小时前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
百***78755 小时前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_942191776 小时前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python