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

显示效果:

相关推荐
花酒锄作田7 小时前
Pydantic校验配置文件
python
hboot8 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi18 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi20 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽20 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户83580861879121 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python