9、Django Admin优化查询

如果你的Admin后台中有很多计算字段,那么你需要对每个对象运行多个查询,这会使你的Admin后台变得非常慢。要解决此问题,你可以重写管理模型中的get_queryset方法使用annotate聚合函数来计算相关的字段。

以下示例为Origin模型的中ModelAdmin管理模型:

python 复制代码
@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):
    list_display = ("name", "hero_count", "villain_count")
    def hero_count(self, obj):
        return obj.hero_set.count()
    def villain_count(self, obj):
        return obj.villain_set.count()

这会在列表视图页面的每行添加两个额外的查询。要解决计算的性能问题,你可以重写get_queryset并使用annotate来进行计算,然后在ModelAdmin方法中使用该annotated聚合字段。

将ModelAdmin管理模型修改如下:

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

每个对象没有额外的查询。你的Admin后台用起来仍像调用annotate聚合函数前一样流畅。

显示效果:

相关推荐
用户7783366132113 小时前
用 React Hook 封装搜索数据:useSerp 的防抖、缓存与错误处理
python·api
65岁退休Coder7 小时前
LangGraph v1.2.9 节点容错策略 & 流式输出 & 持久化记忆管理
后端·python·langchain
ikun_文9 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes9 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明10 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn10 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困10 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao11 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼11 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君11 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python