使用values()获取Django GeometryField的坐标 [英] Get Django GeometryField's coordinates with values()
问题描述
我有一个带GeometryField
的模型.像这样-
I have a model with a GeometryField
. Like this -
from django.contrib.gis.db import models as geo_models
class School(BaseModel):
# Some fields
centroid = geo_models.GeometryField(blank=True, null=True)
我正在使用values()
方法过滤值,因为我必须从QuerySet中生成JSON-
And I'm filtering the values with the values()
method because I have to generate a JSON out of the QuerySet -
class SearchView(View, JSONResponseMixin):
def get(self, *args, **kwargs):
params = self.request.GET
results = {}
schools = School.objects.values('id', 'code', 'name')
# More stuff here
但是我也需要在JSON中返回纬度和经度.将centroid
放在values()
中只会返回加密的十六进制值.我怎样才能把坐标吐出来?
But I need to return the latitude and longitude in the JSON too. Putting centroid
in values()
just returns the encrypted hex value. How do I get it to spit the coordinates out?
推荐答案
经过大量研究,不得不像这样使用PostGIS的ST_AsGeoJSON()
功能-
After much research, had to use the ST_AsGeoJSON()
function of PostGIS like this -
schools = School.objects.extra(
select={
'centroid': 'ST_AsGeoJSON("schools_school"."centroid")'
}
).values('code', 'name', 'centroid')
结果,我得到了与JSON兼容的数据-
As a result, I get the JSON compatible data -
{
"results": [
{
"code": "12345678",
"centroid": "{\"type\":\"Point\",\"coordinates\":[75.32559653,16.906422997]}",
"name": "SCHOOL NAME"
},
// more
]
}
我仍然需要在客户端对它进行反序列化,但是我认为这是可行且可以接受的.至少我得到JSON.
I'd still have to deserialize it on client side, but I guess that's doable and acceptable. At least I get JSON.
这篇关于使用values()获取Django GeometryField的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!