从django PolygonField获取随机点

时间:2017-09-27 18:43:41

标签: python django postgis geodjango

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

1 个答案:

答案 0 :(得分:3)

我在这里回答了类似的问题:Equivalent of PostGIS ST_MakeValid in Django GEOS

由于你本质上想要调用一个数据库函数,你不能像你想象的那样去做 你可以做的是将ST_GeneratePoints包裹为GeoFunc

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

class GeneratePoints(GeoFunc):
    function='ST_GeneratePoints'

并在aggregation/annotation中使用它:

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',
    )
)