从 Django PolygonField 获取随机点
Get random point from django PolygonField
TL,DR; 我想使用 ST_GeneratePoints.
从多边形(可能)中获取随机点
背景
我正在制作一个 GeoDjango 网络服务,并收集了具有各自边界的英国邮政编码,如下所示:
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 小功能 ST_GeneratePoints,它可以在我的 coords
区域中找到随机点。
问题
如何在我的 python django 应用程序中使用此功能(或者您能建议更好的方法吗?)。理想情况下以这样的函数结束:
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
我在这里回答过类似的问题:
既然你本质上是想调用一个数据库函数,你就不能完全按照你想象的去做。
您可以做的是将 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',
)
)
TL,DR; 我想使用 ST_GeneratePoints.
从多边形(可能)中获取随机点背景
我正在制作一个 GeoDjango 网络服务,并收集了具有各自边界的英国邮政编码,如下所示:
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 小功能 ST_GeneratePoints,它可以在我的 coords
区域中找到随机点。
问题
如何在我的 python django 应用程序中使用此功能(或者您能建议更好的方法吗?)。理想情况下以这样的函数结束:
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
我在这里回答过类似的问题:
既然你本质上是想调用一个数据库函数,你就不能完全按照你想象的去做。
您可以做的是将 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',
)
)