我正在构建一个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={})
API当前返回如下内容:
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[..]]]
}
}]
我使用rest_framework_gis.serializers.GeoFeatureModelSerializer
来序列化我的数据。
我看到了以下获取质心的方法:
- 添加一个列质心到我的模型:我不想这样做
- 为我的模型创建一个数据库视图:Django不管理数据库视图,我不想写一个自定义迁移
使用相同的模型并在我的form语句中添加
extra(...)
: 我尝试过,但在序列化中或之前事情变得困难,因为在模型中类型是Polygon
,而质心是Point
。错误如下:TypeError: Cannot set Polygon SpatialProxy (POLYGON) with value of type: <class 'django.contrib.gis.geos.point.Point'>
期望的输出应该是:
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [..]
}
}]
你的意见是什么?
您可以使用以下方法的组合:
-
AsGeoJSON
,其中接受单个地理字段或表达式,并返回几何形状的GeoJSON表示。
-
Centroid()
which接受单个地理字段或表达式,并返回该几何图形的质心值。
-
.annotate()
which用提供的查询表达式列表注释QuerySet中的每个对象。
[…]annotate()
的每个参数都是一个注释,它将被添加到返回的QuerySet中的每个对象中。
例子:
下面的查询:
Polygon.objects.annotate(geometry=AsGeoJSON(Centroid('coordinates')))
将添加一个名为'geometry'
的字段到Polygon
查询集,该查询集将包含从给定模型的每个Polygon
对象的coordinates
字段计算的质心。