ajaysingh ajaysingh - 2 months ago 19
Python Question

Equivalent of PostGIS ST_MakeValid in Django GEOS

Upon checking a polygon object's validity using

Objects.polygon.valid
, it thrown a
GEOS_NOTICE: Self-intersection
error.

I know this can be fixed by using the
ST_MakeValid
method of PostGIS.

I'm using Django 1.11 with GEOS support and can't find its equivalent in Django docs.

Is there any equivalent function for
ST_MakeValid
in Django?

Answer Source

Django version >= 1.10:

Exists the database method: MakeValid

Django version < 1.10:

You can create a custom database function by extending GeoFunc class which by itself extends the Func() class:

from django.contrib.gis.db.models.functions import GeoFunc

class MakeValid(GeoFunc):
    function='ST_MakeValid'

The MakeValid(field_name) applies the ST_MakeValid to the field with field_name.


Usage:

YourModel.objects.get(id=an_id).update(the_geom=MakeValid('the_geom'))

The following is an equivalent query using F() expression to execute the update:

YourModel.objects.get(id=an_id)
                 .update(the_geom=Func(
                     F('the_geom'), 
                     function='ST_MakeValid'
                 ))

Note: the_geom represents your geometry field (point, polygon etc.)