如何限制来自 GeoDjango Postgis django-rest-framework 查询的条目数?

How to limit number of entries from GeoDjango Postgis django-rest-framework query?

我已经通过 this tutorial 构建了基本的 Django 映射功能,但是 Python 不断消耗 32GB 内存 and/or 浏览器崩溃,大概是因为查询不限于前 n 个结果,数据库有数百万个条目。

我的“vietsets.py”:

from rest_framework import viewsets
from rest_framework_gis import filters

from core.models import Tablename
from core.serializers import MarkerSerializer

class MarkerViewSet(viewsets.ReadOnlyModelViewSet):

    bbox_filter_field = "geom"
    filter_backends = (filters.InBBoxFilter,)
    queryset = Tablename.objects.all()
    serializer_class = MarkerSerializer

我认为 InBBoxFilter 需要详细说明,但 the docs 似乎没有提及任何进一步的选择。文档说“如果你正在使用其他过滤器,你会想在你的视图中包含你的其他过滤器后端”给出了例子,filter_backends = (InBBoxFilter, DjangoFilterBackend,),但我只想限制功能的结果数量 InBBoxFilter 已经提供。我可以写一些 DjangoFilterBackend 来限制结果吗?还是通过 django-rest-framework 功能最好地解决这个问题?

如何让它限制结果的数量,或者在使用大型数据库时以其他方式提高性能?

您可以使用 Pagination https://www.django-rest-framework.org/api-guide/pagination/

from rest_framework import viewsets
from rest_framework_gis import filters
from rest_framework.pagination import PageNumberPagination

from core.models import Tablename
from core.serializers import MarkerSerializer

    
class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000


class MarkerViewSet(viewsets.ReadOnlyModelViewSet):

    bbox_filter_field = "geom"
    filter_backends = (filters.InBBoxFilter,)
    queryset = Tablename.objects.all()
    serializer_class = MarkerSerializer
    pagination_class = StandardResultsSetPagination

# request host/api/<your_url>?page=<page_num>&page_size=<page_size>
# will limit size of your response
# and response will include current_page, number_of_elements and  last_page.

改为以下。 restframework_gis.

支持此分页
from rest_framework import viewsets
from rest_framework_gis import filters
from rest_framework_gis.pagination import GeoJsonPagination

from core.models import Tablename
from core.serializers import MarkerSerializer


class MarkerViewSet(viewsets.ReadOnlyModelViewSet):
    bbox_filter_field = "geom"
    filter_backends = (filters.InBBoxFilter,)
    queryset = Tablename.objects.all()
    serializer_class = MarkerSerializer
    pagination_class = GeoJsonPagination

您可以升级服务器或限制结果(分页)。 最合适的分页取决于您的要求。 您可以按某种规则或其他规则对区域进行分组。