Search code examples
djangodjango-rest-frameworkpostgisgeodjango

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


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?


Solution

  • 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.