4👍
✅
Essentially we need to annotate
the intersection
(if any) of each Region
‘s geom
with the given query
. Doing so with a DB query look like this:
from django.db.models import F
from django.contrib.gis.db.models.functions import Intersection
from django.contrib.gis.geos import GEOSGeometry
query = GEOSGeometry(
'{"type":"Polygon","coordinates":[[[-80.983786,43.929011],[-80.511513,43.778458],[-80.291852,44.079184],[-80.775108,44.232127],[-80.983786,43.929011]]]}'
)
results = Region.objects.filter(geom__intersects=query).annotate(
intersection_geom=Intersection(F('geom'), query)
)
Query Explanation:
- Filter the
Regions
that intersect thequery
, using theintersects
spatial lookup. - Calculate the result of
Intersection
between a Region’sgeom
field and thequery
, using theF()
expression to access thegeom
(an explanation onF()
usage can be found in my Q&A example: How to execute arithmetic operations between Model fields in django) annotate
the calculated Intersection into each correspondingRegion
as a field namedintersection_geom
.
After the query execution, the results
will contain each Region
that intersects the query
geom, with the intersection_geom
field containing the exact geometry of the corresponding intersection.
Source:stackexchange.com