Skip to content Skip to sidebar Skip to footer

Relate Two Models By Geometry Intersection In Geodjango

In GeoDjango with two have two models which contain geometry fields: from django.contrib.gis.db import models class Country(models.Model): territory = models.MultiPolygonFiel

Solution 1:

A useful and fairly optimized solution would be to combine the English speaking countries' polygons into a multipolygon (an area produced from at least 2 well defined polygons). Then filter which points intersect with that area.

To do that, we will use GeoDjango's Union:

Returns a GEOSGeometry object comprising the union of every geometry in the queryset. Please note that use of Union is processor intensive and may take a significant amount of time on large querysets

inside a Subquery:

Houses.objects.filter(
    location__intersects=Subquery(
        Country.objects.filter(language='English')
                       .aggregate(area=Union('territory'))['area']
    )
)

Or we can avoid the Subquery (for Django versions < 1.11):

engish_speaking_area = Country.objects.filter(language='English')
                                      .aggregate(area=Union('territory'))['area']
Houses.objects.filter(location__intersects=english_speaking_area)

Another way is to modify a bit of my answer here: GeoDjango query: all point that are contained into a multi polygon to your needs.

Post a Comment for "Relate Two Models By Geometry Intersection In Geodjango"