从Django PolygonField获取随机点 [英] Get random point from django PolygonField

查看:167
本文介绍了从Django PolygonField获取随机点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL,DR 我想使用 ST_GeneratePoints (可能)从多边形中获取随机点. /em>

TL,DR; I want to get a random point from a polygon (potentially) using ST_GeneratePoints.

背景

我正在制作GeoDjango网络服务,并收集了具有各自边界的英国邮政编码,例如:

I'm making a GeoDjango web service and have a collection of UK Postcodes with respective boundaries like so:

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地区.

I've found a delightful little PostGIS function ST_GeneratePoints, which can find me random points in my coords region.

问题

如何在我的python django应用程序中使用此功能(或者您可以提出更好的方法?).理想的情况是以这样的函数结束:

How can I use this function from within my python django app (or can you suggest a better way?). Ideally ending up with a function like so:

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

推荐答案

我在这里回答了类似的问题:

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

由于您本质上是想调用数据库函数,因此您无法像您想象的那样完全做到这一点.
相反,您可以做的是将ST_GeneratePoints包裹为GeoFunc:

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'

并在 aggregation/annotation 中使用它:

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

这篇关于从Django PolygonField获取随机点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆