Get Django GeometryField's coordinates with values()

你离开我真会死。 提交于 2019-12-08 02:29:13

问题


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)

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

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?


回答1:


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

As a result, I get the JSON compatible data -

{
    "results": [
        {
            "code": "12345678",
            "centroid": "{\"type\":\"Point\",\"coordinates\":[75.32559653,16.906422997]}",
            "name": "SCHOOL NAME"
        },
        // more
    ]
}

I'd still have to deserialize it on client side, but I guess that's doable and acceptable. At least I get JSON.



来源:https://stackoverflow.com/questions/18903652/get-django-geometryfields-coordinates-with-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!