Django - 以geoJSON格式获取多边形的质心

Gwy*_*nFR 3 python django postgis django-rest-framework django-rest-framework-gis

我正在构建一个 REST API 来管理与地理相关的数据。
我的前端开发人员想要根据缩放级别以geoJSON格式检索多边形的质心。

我的多边形模型如下:

...
from django.contrib.gis.db import models as geomodels
class Polygon(geomodels.Model):
    fk_owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True)
    external_id = models.CharField(max_length=25, unique=True) 
    func_type = models.CharField(max_length=15)
    coordinates = geomodels.PolygonField(srid=3857)
    properties = JSONField(default={}) 
Run Code Online (Sandbox Code Playgroud)

目前该 API 返回的内容如下:

"type": "FeatureCollection",
"features": [
 {
     "type": "Feature",
     "geometry": {
         "type": "Polygon",
         "coordinates": [[[..]]]
      }
  }]
Run Code Online (Sandbox Code Playgroud)

我用它rest_framework_gis.serializers.GeoFeatureModelSerializer来序列化我的数据。

我看到以下获取质心的方法:

  1. 向我的模型添加一个列质心:我不想这样做
  2. 创建我的模型的数据库视图:Django 不管理数据库视图,我不想编写自定义迁移
  3. 使用相同的模型并将 an 添加extra(...)到我的 orm 语句中:我尝试过,但是在序列化期间或之前事情变得很困难,因为在模型中,类型是Polygon,质心是 a Point。错误如下:

    TypeError: 
        Cannot set Polygon SpatialProxy (POLYGON) with value of type:
        <class 'django.contrib.gis.geos.point.Point'>
    
    Run Code Online (Sandbox Code Playgroud)

预期输出应该是:

"type": "FeatureCollection",
"features": [
 {
     "type": "Feature",
     "geometry": {
         "type": "Point",
         "coordinates": [..]
      }
  }]
Run Code Online (Sandbox Code Playgroud)

你有什么意见 ?

Joh*_*fis 5

您可以结合使用以下方法:

  1. AsGeoJSON, 哪个

    接受单个地理字段或表达式并返回几何图形的 GeoJSON 表示形式。

  2. Centroid()哪个

    接受单个地理字段或表达式并返回几何图形的质心值。

  3. .annotate()哪个

    使用提供的查询表达式列表注释 QuerySet 中的每个对象。
    [...]
    的每个参数annotate()都是一个注释,它将添加到返回的 QuerySet 中的每个对象中。


例子:

以下查询:

Polygon.objects.annotate(geometry=AsGeoJSON(Centroid('coordinates')))
Run Code Online (Sandbox Code Playgroud)

将添加一个名为查询集的字段'geometry'Polygon该字段将包含根据给定模型的coordinates每个对象的字段计算的质心。Polygon