Alvaro
Alvaro

Reputation: 12037

Finding models inside a set of Polygons in GeoDjango

I have a bunch of polygon-based regions:

regions = Region.objects.filter(criteria=criteria)

The model is defined as such:

class Region(models.Model):
    poly = models.PolygonField()

I have a point-based model, like this one:

class Example(models.Model):
    point = models.PointField()

Is there a way to get all instances of Example that fall inside any of the polygons in the queryset? I can't find any info related to this in the docs.. Thanks in advance!

Upvotes: 2

Views: 969

Answers (1)

Spoutnik16
Spoutnik16

Reputation: 864

models.py :

from django.contrib.gis import models

class Example(models.Model):
    point = models.PointField()
    objects = models.GeoManager()

You build a multipolygon out of all those regions, and ask what example is inside that multipolygon

from django.contrib.gis.geos import MultiPolygon

list_poly = [reg.poly for reg in Region.objects.filter(criteria=criteria)]
multipolygon = MultiPolygon(list_poly)
list_examples = Example.objects.filter(point__within=multipolygon)

Upvotes: 4

Related Questions