Django Rest Framework分页计数极慢 [英] Django Rest Framework pagination extremely slow count

查看:26
本文介绍了Django Rest Framework分页计数极慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django Rest 框架中打开了分页,但它似乎非常慢.Count 看起来像是罪魁祸首,由于表中有数百万行,因此每次返回都要花费数百毫秒.

I turned pagination on in Django Rest framework and it appears to be incredibly slow. Count looks like the culprit, and is taking hundreds of milliseconds to return each time due to the millions of rows in the tables.

我使用 postgresql 作为数据库.有没有办法不计算行数并仍然使用分页?如果我手动过滤查询集,则在启用此功能之前性能很好.

I am using postgresql as the database. Is there any way to not count the rows and still use pagination? The performance was fine before this was enabled if I manually filtered the queryset.

推荐答案

覆盖分页类的 get_paginated_response 方法,并且不包括计数.可以参考基本实现PageNumberPagination 类,看看你应该返回什么.

Override the get_paginated_response method of your pagination class, and do not include the count. You can refer to the base implementation of the PageNumberPagination class to see what you should return.

from rest_framework.pagination import PageNumberPagination
from collections import OrderedDict # requires Python 2.7 or later

class PageNumberPaginationWithoutCount(PageNumberPagination):
    # Set any other options you want here like page_size

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ]))

然后在您的 settings.py 中,将 DEFAULT_PAGINATION_CLASS 设置为您的新分页类.

Then in your settings.py, set DEFAULT_PAGINATION_CLASS to your new pagination class.

DEFAULT_PAGINATION_CLASS = 'path.to.PageNumberPaginationWithoutCount'

此方法用于分页文档中的示例.

从下面的评论看来,这可能不足以防止慢速 sql 查询,因此您可能还需要覆盖 paginate_queryset.

from the comments below it sounds like this might not be enough to prevent the slow sql query, so you might need to override paginate_queryset as well.

这篇关于Django Rest Framework分页计数极慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆