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聚合函数前一样流畅。

显示效果:

相关推荐
专注仿真1 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
Best-Wishes1 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停2 小时前
自动化测试(java)
java·开发语言·selenium·自动化
Smoothcloud润云2 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook3 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴3 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
诺伦3 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost3 小时前
pytorch学习笔记1
python·学习方法
鬼手点金4 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
爱上网的小舟4 小时前
星际战士2启动错误怎么办?5种游戏报错解决方法
开发语言·php