<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Adedeji Publication]]></title><description><![CDATA[Adedeji Publication]]></description><link>https://adedejimakinde.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:02:22 GMT</lastBuildDate><atom:link href="https://adedejimakinde.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building a Spatial Decision Support System with Django, PostGIS, and Scikit-Learn]]></title><description><![CDATA[A complete guide to building spatial decision support systems (SDSS) using Python, Django, PostGIS, and machine learning with Scikit-learn.]]></description><link>https://adedejimakinde.hashnode.dev/building-a-spatial-decision-support-system-with-django-postgis-and-scikit-learn</link><guid isPermaLink="true">https://adedejimakinde.hashnode.dev/building-a-spatial-decision-support-system-with-django-postgis-and-scikit-learn</guid><dc:creator><![CDATA[Adedeji Makinde]]></dc:creator><pubDate>Sat, 25 Jul 2026 09:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a71a3d75ce1f6346f3cce88/5f606084-aa24-46d8-bc8c-64df320c80e8.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Modern SaaS applications rely on relational databases for authentication, text data and every other backend element. But a normal database struggles the moment a system has to answer a question like "Which students live inside this flood zone?" or "What is the fastest bus route for these forty scattered coordinates?"</p>
<p>That was the main engineering challenge behind the spatial routing component of Classnode, a multi-tenant school management platform. To solve it, I needed a Spatial Decision Support System (SDSS) that takes in raw geographic data, runs machine learning algorithms on that data and serves the improved results through a REST API.</p>
<p>In this article I will walk you through the backend architecture of that system. We will look at how to configure PostgreSQL with the PostGIS extension for spatial queries, how to model geometries like Polygons and LineStrings in Django, and how to use a Scikit-Learn K-Means clustering algorithm to group student locations into optimised transport routes.</p>
<h3>Engineering the Spatial Database (PostGIS and Django)</h3>
<p>A standard PostgreSQL database cannot handle geographic data on its own, so it needs the PostGIS extension. Once the database is provisioned, the first step is to point the Django configuration at the spatial backend instead of the standard relational one:</p>
<pre><code class="language-python">DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        # ... standard database credentials
    }
}
</code></pre>
<p>With the engine configured, we can move past ordinary text fields and model real-world geometries. Classnode needs three distinct types of spatial data: the pinpointed location of each student, the outline of every environmental hazard area, and the traced path of each transit route.</p>
<p>Importing <code>django.contrib.gis.db.models</code> lets us assign geometric properties directly to our database tables:</p>
<pre><code class="language-python">from django.contrib.gis.db import models as gis_models
from django.db import models

class HazardZone(models.Model):
    name = models.CharField(max_length=100)
    geom = gis_models.PolygonField()

class BusRoute(models.Model):
    route_name = models.CharField(max_length=100)
    path = gis_models.LineStringField()

class LocationGis(models.Model):
    student = models.ForeignKey('Student', on_delete=models.CASCADE)
    geom = gis_models.PointField()
</code></pre>
<p>Defining these specific field types (<code>PolygonField</code>, <code>LineStringField</code>, and <code>PointField</code>) ensures the database natively understands the spatial relationships between them. This is what makes it possible to run rapid queries later, such as checking if a student's coordinate intersects with a defined hazard zone.</p>
<p>However, raw coordinate data is difficult for administrators to manage manually. To solve this, we can override the default map widgets in the Django admin panel, utilizing the OpenStreetMap widget (<code>OSMWidget</code>) to enforce the correct drawing tools and center the map on a specific default coordinate:</p>
<pre><code class="language-python">from django.contrib.gis import admin
from django.contrib.gis.db import models as gis_models
from .models import HazardZone

@admin.register(HazardZone)
class HazardZoneAdmin(admin.ModelAdmin):
    formfield_overrides = {
        gis_models.GeometryField: {'widget': admin.OSMWidget(attrs={
            'geom_type': 'POLYGON',
            'default_lon': 3.3792,
            'default_lat': 6.5244,
            'default_zoom': 11,
        })},
    }
</code></pre>
<p>This replaces the text inputs for a clean, interactive map in the backend. Data integrity is enforced right at the entry point so the inputs are already clean before anything reaches the machine learning pipeline.</p>
<h3>Integrating the Machine Learning Engine</h3>
<p>The geographic data is now stored and queryable. The next step is turning those raw coordinates into routing intelligence.</p>
<p>When determining bus routes, the goal is to group students who live near each other and assign one vehicle to each group. We have no pre-labelled training data telling us which student belongs to which bus, so this is an unsupervised learning problem. The Scikit-Learn K-Means clustering algorithm handles this kind of spatial optimisation very well.</p>
<p>By pulling the latitude and longitude out of our PostGIS <code>PointField</code>, we can feed a two-dimensional array of coordinates straight into Scikit-Learn:</p>
<pre><code class="language-python">import numpy as np
from sklearn.cluster import KMeans
from .models import LocationGis

def generate_bus_routes(num_buses):
    # 1. Extract coordinates from the spatial database
    student_locations = LocationGis.objects.all()
    coordinates = np.array([
        [loc.geom.y, loc.geom.x] for loc in student_locations
    ])

    # 2. Initialize the K-Means algorithm
    # n_clusters represents the number of available buses
    kmeans = KMeans(n_clusters=num_buses, random_state=42, n_init=10)

    # 3. Fit the model to the spatial data
    cluster_labels = kmeans.fit_predict(coordinates)

    # 4. Map the AI-generated clusters back to the students
    clustered_routes = []
    for index, student in enumerate(student_locations):
        clustered_routes.append({
            'student_id': student.student.id,
            'route_group': int(cluster_labels[index])
        })
        
    return clustered_routes
</code></pre>
<p>In this pipeline, the algorithm calculates the spatial variance between all student locations and iteratively finds the mathematical center (centroid) for each route. The <code>n_clusters</code> parameter dynamically adapts to the school's available fleet size. Once the model processes the array, the resulting <code>cluster_labels</code> serve as our optimized route IDs, instantly mapping each student to their most efficient bus assignment.</p>
<h3>Bridging the Gap: REST APIs and the Frontend</h3>
<p>Calculating the clusters is only half the work. The other half is getting those insights in front of the people who need them.</p>
<p>The system uses the Django REST Framework (DRF) with its GIS extension, <code>djangorestframework-gis</code>. Plain JSON does not suit geographic data, so the API serialises the PostGIS models into GeoJSON, which is the web standard for spatial features.</p>
<p>A <code>GeoFeatureModelSerializer</code> converts our database models into a frontend-ready format:</p>
<pre><code class="language-python">from rest_framework_gis.serializers import GeoFeatureModelSerializer
from .models import LocationGis

class LocationSerializer(GeoFeatureModelSerializer):
    class Meta:
        model = LocationGis
        geo_field = "geom"
        fields = ('id', 'student')
</code></pre>
<p>When the client requests the <code>/api/locations/</code> endpoint, the Django server responds with a properly formatted GeoJSON <code>FeatureCollection</code>.</p>
<h3>Designing the Spatial Dashboard</h3>
<p>Visualizing this data requires a careful approach to the frontend interface. Geographic data is very complex, so the UI should not struggle with the map for the user's attention.</p>
<p>Adopting a high-density, utility-first UI design system; taking visual and structural cues from modern SaaS platforms like Attio; ensures that school administrators can process dense clusters of geographic points without feeling overwhelmed. By stripping away unnecessary padding, utilizing compact data tables alongside the map, and employing strict visual hierarchies, the dashboard allows the spatial data and the AI-generated routing clusters to remain the primary focus.</p>
<h3>Conclusion &amp; Next Steps</h3>
<p>Building a Spatial Decision Support System requires a fundamental shift in how you treat your database. By migrating from standard relational tables to PostGIS geometries, and leveraging Scikit-Learn to extract actionable intelligence from those coordinates, Classnode transforms raw student addresses into an optimized logistical network.</p>
<p>The transition from local development to a live cloud environment introduces its own set of challenges, from handling Docker container sleep states to securely provisioning remote superusers but the resulting architecture is highly scalable and ready for production.</p>
<p>You can find the complete source code for this spatial decision support system on my GitHub repository here: <a href="https://github.com/adedejimakinde/luffy_sdss">View the source code</a></p>
]]></content:encoded></item></channel></rss>