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

Viewed 126

I've built basic Django mapping functionality through this tutorial but Python keeps blowing through 32GB of ram and/or the browser crashes, presumably because the query isn't limited to the first n results and the DB has millions of entries.

My "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

I think InBBoxFilter needs to be elaborated upon but the docs don't seem to mention any further options. The docs say "if you are using other filters, you’ll want to include your other filter backend in your view" giving the example, filter_backends = (InBBoxFilter, DjangoFilterBackend,), but I only want to limit the number of results for the functionality InBBoxFilter already provides. Can I write some kind of DjangoFilterBackend to limit results? Or is this best addressed through django-rest-framework functionality?

How can I tell it to limit the number of results, or otherwise improve performance when using big databases?

2 Answers

Change to below. This pagination is supported by 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

You can upgrade your server or limit the result(pagination). Most appropriate pagination is up to your request. You can grouping area by some rule or whatever.

You can use 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.
Related