TL,博士;我想用https://postgis.net/docs/ST_GeneratePoints.html从多边形(潜在的)得到一个随机点。
背景
我正在制作一个GeoDjango web服务,并有一组英国邮政编码,其各自的边界如下:
from django.db import models as dj_models
from django.contrib.gis.db import models as gis_models
class Postcode(gis_models.Model):
pretty_postcode = dj_models.CharField( max_length=8 )
coords = gis_models.PolygonField( default='POLYGON EMPTY' )我找到了一个可爱的小PostGIS函数GeneratePoints,它可以在我的coords区域找到随机点。
问题
如何在python应用程序中使用这个函数(或者您可以提出更好的方法)。理想情况下,以这样的函数结束:
from django.contrib.gis import geos
# ... other imports ...
class Postcode(gis_models.Model):
# ... fields ...
def get_random_point(self):
rand_point = # code that executes ST_GeneratePoints
# and returns a geos.Point instance
return rand_point发布于 2017-09-28 08:25:29
我在这里回答了一个类似的问题:Django GEOS中的MakeValid
因为您实际上想调用一个数据库函数,所以您不能像您想象的那样那样做。
相反,您可以将ST_GeneratePoints包装为一个GeoFunc。
from django.contrib.gis.db.models.functions import GeoFunc
class GeneratePoints(GeoFunc):
function='ST_GeneratePoints'from django.db.models import Value
Postcode.objects.annotate(
rand_point=GeneratePoints(
'coords',
Value(1) # to get only one point
)
)做同样事情的另一种方法是:
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',
)
)https://stackoverflow.com/questions/46455081
复制相似问题