Reputation: 14929
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?
Upvotes: 3
Views: 1315
Reputation: 14929
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.
Upvotes: 3