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'

显示效果:

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

相关推荐
酷飞飞1 天前
Python网络与多任务编程:TCP/UDP实战指南
网络·python·tcp/ip
数字化顾问1 天前
Python:OpenCV 教程——从传统视觉到深度学习:YOLOv8 与 OpenCV DNN 模块协同实现工业缺陷检测
python
学生信的大叔1 天前
【Python自动化】Ubuntu24.04配置Selenium并测试
python·selenium·自动化
计算机编程小央姐1 天前
跟上大数据时代步伐:食物营养数据可视化分析系统技术前沿解析
大数据·hadoop·信息可视化·spark·django·课程设计·食物
用户21411832636021 天前
Qwen3-Coder 实战!历史人物短视频一键生成,多分镜人物不崩,魔搭直接玩
后端
追逐时光者1 天前
C#/.NET/.NET Core技术前沿周刊 | 第 54 期(2025年9.8-9.14)
后端·.net
追逐时光者1 天前
C#/.NET/.NET Core编程技巧练习集,配套详细的文章教程讲解!
后端·.net
诗句藏于尽头1 天前
Django模型与数据库表映射的两种方式
数据库·python·django
智数研析社1 天前
9120 部 TMDb 高分电影数据集 | 7 列全维度指标 (评分 / 热度 / 剧情)+API 权威源 | 电影趋势分析 / 推荐系统 / NLP 建模用
大数据·人工智能·python·深度学习·数据分析·数据集·数据清洗
扯淡的闲人1 天前
多语言编码Agent解决方案(5)-IntelliJ插件实现
开发语言·python