Here's a sample PostGIS query I use to get geometries within four points:

FROM myTable
WHERE ST_MakeEnvelope(-97.82381347656252, 30.250444940663296, -97.65901855468752, 30.29595835209862, 4326) && ST_Transform(myTable.geom,4326);

With this query, I can get all rows within those four points. How do I execute this query or similar queries in Django or GeoDjango?

EDIT: I must also note that my geom column is a MultiPolygon type.


There are many ways to go about it, but a straight-forward one is to use Django's connection object:

from django.db import connection

This creates a direct connection to your database. With this, you can either execute direct SQL queries:

cursor = connection.cursor()
bbox = (97.82, 30.25, -97.65, 30.29)
cursor.execute("SELECT * FROM myTable WHERE ST_MakeEnvelope(%s, %s, %s, %s, 4326) && ST_Transform(myTable.geom, 4326)", bbox)
result = cursor.fetchall()

Or you can pass your query to a function using Postgres' plpgsql (calling it, say, fn_grab_polys_bbox), and execute it:

cursor = connection.cursor()
bbox = (97.82, 30.25, -97.65, 30.29)
cursor.callproc('fn_grab_polys_bbox', bbox)
result = cursor.fetchall()

Django's connection object is actually referencing Python's own DB-API, which works with a variety of databases. Hence, if you need to call a function, or a table, from a different database than the one you set for your project, you can even do a specific connection to that and repeat the above steps, the returned objects will be the same.

from django.contrib.gis.gdal.envelope import Envelope
bbox=Envelope((97.82381347656252, 30.250444940663296, -97.65901855468752, 30.29595835209862))

from https://docs.djangoproject.com/en/2.0/ref/contrib/gis/geos/#django.contrib.gis.geos.GEOSGeometry.envelope

  • 1
    How would I query myTable with this? – Username Jan 7 '18 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.