GeoDjango Query: All Point That Are Contained Into A Multi Polygon
Solution 1:
From Django version 1.11 you have an optimized option to solve this query.
Assumptions:
Model_Ahas a geometry field called:model_a_point.Model_Bhas a geometry field called:model_b_poly.
Methods used:
Subquery(), new method in Django 1.11 which allows the definition of queries with a subquery part.OuterRef(), new method in Django 1.11 which is used:when a queryset in a Subquery needs to refer to a field from the outer query.
within(), which:Tests if the geometry field is spatially within the lookup geometry.
annotate(), which will generate for each item in a queryset, a new field (in our case it will contain the points contained by a polygon.)
Query:
Model_B.objects.annotate(
contained_points=Subquery(
Model_A.objects.filter(
model_a_point__within=OuterRef('model_b_poly')
) # Ref: 1, referenced below, keep reading
)
)
Result and something more:
The query above will have a field contained_points for every polygon in Model_B which contains every point from Model_A contained by this polygon.
If you only want to keep geometry field of those points (lon, lan), at the end of the Subquery call (Ref: 1), use the values() method.
Post a Comment for "GeoDjango Query: All Point That Are Contained Into A Multi Polygon"