You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django REST Framework统计SQL查询数及Debug Toolbar不显示问题咨询

问题根因

django-debug-toolbar默认仅会在Content-Type为text/html的响应中注入工具栏的前端资源,你返回的JsonResponse默认类型是application/json,因此不会触发工具栏注入逻辑。当你抛出Http404时,Django默认返回HTML格式的错误页,符合toolbar的注入条件,所以可以正常展示。

解决方案

根据你的需求,可选择以下两种实现方式,均无需修改现有视图代码:

方案1:全局中间件统计SQL数量(优先推荐)

如果仅需要统计SQL查询数量,不需要可视化调试工具栏,直接自定义全局中间件即可自动统计所有接口的SQL执行情况:

  1. 在项目任意app下新建middleware.py文件,添加如下代码:
from django.db import connection
from django.conf import settings

class SQLCountMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        # 仅调试模式下生效,不影响生产环境
        if settings.DEBUG:
            # 统计当前请求执行的SQL总数
            sql_count = len(connection.queries)
            # 可选1:将SQL数量写入响应头,在浏览器开发者工具可直接查看
            response['X-SQL-Count'] = str(sql_count)
            # 可选2:直接打印到控制台
            print(f"请求路径 {request.path} 执行SQL数量:{sql_count}")
            # 可选3:需要查看具体SQL时,可打印 connection.queries 完整内容
        return response
  1. 打开项目settings.py,在MIDDLEWARE列表的最顶部添加该中间件:
MIDDLEWARE = [
    '你的app名称.middleware.SQLCountMiddleware',
    # 其余原有中间件保持不变
]

方案2:适配django-debug-toolbar支持JSON响应显示

如果需要使用debug toolbar的完整调试功能,可以通过中间件将JSON响应临时包装为HTML格式,仅调试模式下生效:

  1. 在middleware.py中添加如下代码:
from django.conf import settings
from django.http import JsonResponse

class WrapJsonToHtmlMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if settings.DEBUG and isinstance(response, JsonResponse):
            # 将JSON内容嵌入HTML的pre标签中,保持内容可读性的同时满足toolbar的注入要求
            json_content = response.content.decode('utf-8')
            response.content = f"<html><body><pre>{json_content}</pre></body></html>"
            response['Content-Type'] = 'text/html'
        return response
  1. 在settings.py的MIDDLEWARE列表中,将该中间件放在debug_toolbar.middleware.DebugToolbarMiddleware的上方即可。

注:使用该方案需确保settings.py中INTERNAL_IPS配置包含你访问服务的IP(本地开发通常需添加127.0.0.1)。

内容的提问来源于stack exchange,提问作者RoyalBosS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:54:05