python - 怎样优化models.objects.all() ?
PHPz
PHPz 2017-04-18 09:28:19
0
3
369

先看代码
views.py:

def vms(request):
    user = request.user
    servers = List.objects.all()
    return render_to_response(
        'vmserver/all_vms.html', {
            'list': servers,
            'user': user,
        }
    )

template:

<p class="dataTable_wrapper">
   <table class="table table-striped table-bordered table-hover" id="dataTables-example" width="100%">
    <thead>
    <tr>
        <th>主机名</th>
        <th>IP地址</th>
        <th>应用名称</th>
        <th>CPU</th>
        <th>内存</th>
        <th>磁盘</th>
        <th>操作系统</th>
        <th>电源</th>
        <th>配置项</th>
    </tr>
    </thead>
    <tbody>
    {% for vm in list %}
        <tr class="odd gradeX">
        <td><a href="/vmserver/vms/{{ vm.id }}/$">{{ vm.list_name }}</a></td>
        <td>{{ vm.ip }}</td>
        <td>{{ vm.app_name }}</td>
        <td>{{ vm.cpu }}</td>
        <td>{{ vm.mem }}</td>
        <td>{{ vm.total_hard_disk }}</td>
        <td>{{ vm.os }}</td>
        <td>{{ vm.power_status }}</td>
        <td>
            '''

由于我的List表中有2000多条数据,通过datatables插件渲染数据的时候,响应非常慢,需要10秒左右前端才能渲染完成,请问有什么优化的方法,能让速度更快。

PHPz
PHPz

学习是最好的投资!

reply all(3)
Ty80

Paging should be completed in the background, because you get all 2000多条数据传给前台,前台在生成页面的时候就要加载这2000多条数据,如果分页在后台完成,每次只传给前台当前页面的,譬如50 pieces of data in the background, and the page will naturally become faster when rendering.

You can try this first to see if what I said is right:

def vms(request):
    user = request.user
    # .all()方法会获取所有数据,这里只取前50个传递给前端
    servers = List.objects.all()[:50]
    return render_to_response(
        'vmserver/all_vms.html', {
            'list': servers,
            'user': user,
        }
    )

I only added one [:50].all()方法依然会获取所有2000条数据,只是传给前端的只有50条,如果这样一来你的前端渲染速度变快了,那证明速度本身和objects.all()to the above code. It has nothing to do with it. It is only related to the amount of data received by the front end.

In the actual process, background paging is slightly more complicated than this. If my conclusion above is ok, I will update it again...

伊谢尔伦

Add caching, add indexing, and add paging

Ty80

If you use Django Restframework, you can use the paging function natively provided by the framework:

Refer: http://www.django-rest-framew...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!