【问题标题】:Get random point from django PolygonField从 django PolygonField 获取随机点
【发布时间】:2018-03-09 08:48:41
【问题描述】:

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

【问题讨论】:

    标签: python django postgis geodjango


    【解决方案1】:

    我在这里回答了类似的问题: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',
        )
    )
    

    【讨论】:

      猜你喜欢
      • 2012-08-13
      • 1970-01-01
      • 2020-06-10
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2020-06-03
      • 2022-01-06
      相关资源
      最近更新 更多