Skip to content Skip to sidebar Skip to footer

Get Random Point From Django PolygonField

TL,DR; I want to get a random point from a polygon (potentially) using ST_GeneratePoints. Background I'm making a GeoDjango web service and have a collection of UK Postcodes with

Solution 1:

I have answered a similar question here: Equivalent of PostGIS ST_MakeValid in Django GEOS

Since you essentially want to call a database function, you cannot quite do it as you imagine.
What you can do instead is to wrap the ST_GeneratePoints as a GeoFunc:

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

class GeneratePoints(GeoFunc):
    function='ST_GeneratePoints'

and use it in an aggregation/annotation:

from django.db.models import Value

Postcode.objects.annotate(
    rand_point=GeneratePoints(
        'coords',
        Value(1) # to get only one point
    )
)

Another way of doing the same thing is:

from django.contrib.gis.db.models.functions import GeoFunc
from django.db.models import F, Value

Postcode.objects.annotate(
    rand_point=GeoFunc(
        F('coords'),
        Value(1),
        function='ST_GeneratePoints',
    )
)

Post a Comment for "Get Random Point From Django PolygonField"