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'

显示效果:

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

相关推荐
m0_5648768420 分钟前
提示词工程手册学习
人工智能·python·深度学习·学习
波诺波38 分钟前
p1项目system_model.py代码
开发语言·python
静心观复1 小时前
Python 虚拟环境与 pipx 详解
开发语言·python
卷心菜狗1 小时前
Re.从零开始使用Python构建本地大模型网页智慧聊天机器人
开发语言·python·机器人
书到用时方恨少!1 小时前
Python NumPy 使用指南:科学计算的基石
开发语言·python·numpy
bilI LESS2 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
web前端进阶者2 小时前
Rust初学知识点快速记忆
开发语言·后端·rust
L-李俊漩2 小时前
荆华密算 面试题(大模型开发)
python
小陈工2 小时前
Python Web开发入门(十):数据库迁移与版本管理——让数据库变更可控可回滚
前端·数据库·人工智能·python·sql·云原生·架构
JoshRen2 小时前
Python中的简单爬虫
爬虫·python·信息可视化