top of page

Spatial Querying with Django REST API: Filtering, Bounding Box, and Nearest Feature

Updated: Jul 1

Introduction

Imagine building an application that shows the nearest hospitals to a user, filters restaurants within a city, or displays properties within a specific boundary on a map. To do this effectively, your backend must understand spatial data—and how to query it. This is where Django combined with PostGIS and Django REST Framework shines.


In this blog, you'll learn how to build and enhance a Spatial REST API using Django to support geospatial filtering, bounding box queries, and finding the nearest feature. By the end, you'll know how to integrate powerful spatial querying into your Django application to support location-aware features.

1. Prerequisites and Setup

Before diving in, ensure you have the following installed:

  • Python 3.x

  • PostgreSQL with PostGIS extension

  • Django

  • Django REST Framework

  • django.contrib.gis (comes with Django)

Install required packages:

Install required packages
pip install Django djangorestframework psycopg2-binary djangorestframework-gis

Update your INSTALLED_APPS and DATABASES config:

Update your INSTALLED_APPS and DATABASES config
Update your INSTALLED_APPS and DATABASES config 1
2. Defining a Spatial Model

Example model to store locations:

Example model to store locations

Run migrations:

python manage.py makemigrations
python manage.py makemigrations
python manage.py migrate
python manage.py migrate
3. Creating the REST API

Serializer:

Serializer

View:

View

URL Configuration:

URL Configuration:
4. Query Examples
Example queries:
  • Bounding Box Filter:

    GET /places/?in_bbox=77.50,12.90,77.65,13.05

  • Nearest Places:

    GET /places/?near=77.5946,12.9716

  • Combined Filter:

    GET /places/?in_bbox=77.50,12.90,77.65,13.05&near=77.59,12.97

5. Real Use Case: Bengaluru Bus Stops

Demonstrates filtering and nearest querying of BMTC bus stops in Bengaluru.

6. Bonus: Adding Pagination and Radius Filter

Example: Nearby places within 2km

from django.contrib.gis.measure import D


# Add this inside get_queryset()

if near:

...

queryset = queryset.filter(location__distance_lte=(user_location, D(km=2)))


Outputs :

Postgres

Postgres
Place List

Json

Json

Conclusion

With Django, PostGIS, and Django REST Framework, building a robust spatial API is not only possible but incredibly efficient. You now know how to:

  • Set up geospatial models

  • Create APIs for location-based queries

  • Use bounding boxes and nearest filters for spatial intelligence

Whether you're building a ride-hailing app, a real estate platform, or a delivery tracking system, these tools empower you to provide real-time, geolocation-based services effectively.


Comments


bottom of page