我正在构建一个用于管理地理相关数据的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
来序列化我的数据。
我看到以下几种方法可以获取质心:
- Add a column centroid to my model: I don't want to do this
- Create a database view of my model: Django does not manage database views and I don't want to write a custom migration
Use the same model and add an
extra(...)
to my orm statement: I tried but things get hard in or before serialization, because in the model the type isPolygon
, and the centroid is aPoint
. The error is the following: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": [..]
}
}]
您的意见是什么?