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'

显示效果:

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

相关推荐
qq_297574671 小时前
【实战教程】SpringBoot 集成阿里云短信服务实现验证码发送
spring boot·后端·阿里云
rayufo1 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
韩立学长2 小时前
【开题答辩实录分享】以《智能大学宿舍管理系统的设计与实现》为例进行选题答辩实录分享
数据库·spring boot·后端
Python 老手3 小时前
Python while 循环 极简核心讲解
java·python·算法
开源技术3 小时前
如何将本地LLM模型与Ollama和Python集成
开发语言·python
weixin_437044643 小时前
Netbox批量添加设备——堆叠设备
linux·网络·python
我有医保我先冲3 小时前
AI 时代 “任务完成“ 与 “专业能力“ 的区分:理论基础、行业影响与个人发展策略
人工智能·python·机器学习
测试开发Kevin4 小时前
小tip:换行符CRLF 和 LF 的区别以及二者在实际项目中的影响
java·开发语言·python
爱学习的阿磊4 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
阿狸OKay4 小时前
einops 库和 PyTorch 的 einsum 的语法
人工智能·pytorch·python