Django开发中Product表有4.4万实例时,前端DataTable加载慢如何优化
Django大数据量Product表格渲染优化方案
当前实现的核心瓶颈为:服务端一次性返回全部44000条数据、前端生成对应数量的DOM节点,仅靠前端DataTable做分页,会导致网络传输体积过大、DOM渲染耗时久、JS解析效率低。核心优化方向为改为服务端分页模式,按需加载当前页数据,具体实现步骤如下:
一、前端改造(table.html)
1. 开启DataTable服务端分页配置
替换原有DataTable初始化代码,改为通过AJAX按需请求分页数据:
$('#mydatatable').DataTable({ pagingType: 'full_numbers', serverSide: true, // 开启服务端分页模式 processing: true, // 显示数据加载中的过渡提示 ajax: { url: '/api/product-list/', // 对应后端数据接口地址,需与urls.py配置匹配 type: 'GET', dataSrc: 'data' // 匹配后端返回JSON中的数据字段名 }, columns: [ { data: 'image_html' }, // 第一列:产品图片(含详情页跳转链接) { data: 'product_name' }, // 第二列:产品名称 { data: 'num_art' } // 第三列:产品编号 ] });
2. 清空原有服务端渲染的表格内容
删除原有tbody中遍历product_list的循环代码,表格数据将由DataTable通过AJAX动态渲染:
<div class="container mb-5 mt-3"> <table class="table table-striped table-bordered" style="width: 100%" id="mydatatable"> <thead> <tr> <th>Image produit</th> <th>Nom du produit</th> <th>Num_art</th> </tr> </thead> <tbody> <!-- 数据由前端动态加载,不再服务端循环生成 --> </tbody> <tfoot> </tfoot> </table> </div>
二、后端数据接口实现
1. 配置路由(urls.py)
新增产品列表数据接口的路由:
from django.urls import path from . import views urlpatterns = [ # 原有业务路由保留 path('api/product-list/', views.product_list_api, name='product_list_api'), ]
2. 编写接口视图(views.py)
视图需解析DataTable传递的分页、搜索、排序参数,返回符合DataTable要求的JSON格式数据:
from django.http import JsonResponse from django.urls import reverse from django.templatetags.static import static from .models import Product def product_list_api(request): # 解析DataTable传递的请求参数 draw = int(request.GET.get('draw', 0)) start = int(request.GET.get('start', 0)) page_size = int(request.GET.get('length', 10)) search_keyword = request.GET.get('search[value]', '').strip() order_column_idx = int(request.GET.get('order[0][column]', 1)) order_direction = request.GET.get('order[0][dir]', 'asc') # 前端列索引与模型字段的映射规则(与columns顺序一一对应) column_field_map = { 1: 'product_name', 2: 'num_art' } # 处理排序逻辑 order_field = column_field_map.get(order_column_idx, 'product_name') order_field = f'-{order_field}' if order_direction == 'desc' else order_field # 基础查询集:仅取表格需要的字段,减少不必要的数据库开销 base_queryset = Product.objects.only('id', 'product_name', 'num_art', 'image_product') # 处理搜索过滤逻辑 if search_keyword: base_queryset = base_queryset.filter( product_name__icontains=search_keyword ) | base_queryset.filter( num_art__icontains=search_keyword ) # 计算总条数、过滤后总条数 total_count = Product.objects.count() filtered_count = base_queryset.count() # 分页获取当前页数据 page_products = base_queryset.order_by(order_field)[start:start + page_size] # 组装为DataTable要求的数据格式 data_list = [] for product in page_products: # 复用原有图片展示逻辑 if str(product.image_product) != 'anomalie/0.jpg': img_url = product.image_product.url else: img_url = static('images/unknown_anomalie.png') # 复用原有详情页跳转逻辑 detail_url = reverse('consult_product_view', kwargs={'pk': product.id}) data_list.append({ 'image_html': f'<a href="{detail_url}"><img class="img-responsive image-rezise check" src="{img_url}" loading="lazy"></a>', 'product_name': product.product_name, 'num_art': product.num_art }) return JsonResponse({ 'draw': draw, 'recordsTotal': total_count, 'recordsFiltered': filtered_count, 'data': data_list })
三、额外性能优化项
- 给搜索、排序字段加数据库索引:修改models.py中对应字段,添加
db_index=True,例如:
修改后执行product_name = models.CharField( max_length=60, null=False, blank=False, db_index=True) num_art = models.IntegerField(null=False, blank=False, db_index=True)python manage.py makemigrations和python manage.py migrate生效。 - 缓存总条数:如果Product数据非高频实时更新,可使用Django自带缓存短时存储总条数,避免每次请求都执行全表count操作:
from django.core.cache import cache # 替换原有的total_count获取逻辑 total_count = cache.get('product_total_count') if not total_count: total_count = Product.objects.count() cache.set('product_total_count', total_count, 300) # 缓存300秒 - 图片原生懒加载:上述代码中已为img标签添加
loading="lazy"属性,利用浏览器原生能力减少首屏资源请求量。
内容的提问来源于stack exchange,提问作者Lady Geraldine Villamil Guerre
相关产品推荐
相关产品推荐

