Check if a point is in a MultiPolygonField

Hello agian :slight_smile:
I’ve created a simple model called ProvincialBorders where I’ve imported the GEOJSON file from this link: GeoJSON for South African provincial boundaries · GitHub
That gives me the borderes of all the provinces in South Africa and it works as I expected.

class ProvincialBorders(models.Model):
province = models.CharField(max_length=100)
geom = models.MultiPolygonField()

I have another model where I have single PointField.

class Bird(models.Model):
name = models.CharField(max_length=100)
location = models.PointField()

How can I check if the value of the Point is inside of the MultiPolygonField? If you can point me in the right direction it would be very much appriciated. Thanks

In the past I have used PyGEOS for this, but now it appears that the Shapely library would be the current tool-of-choice.

Also see:

I don’t think we need yet another lib to achieve that. The GeoDjango queryset API offers plenty of operators to check various geographic relationships between model fields (GIS QuerySet API Reference | Django documentation | Django).

e.g. all birds in a specific province: Bird.objects.filter(location__within=province.geom)
the province containing a bird: province.objects.get(geom__contains=bird.location)
etc.

2 Likes

Wow that is perfect, thank you so much