django - GeoDjango: Distance Object is not serializable -
i learning geo-django. can find out distance of places point. when use .values
method annotated distance
field, getting
typeerror: object of type 'distance' not json serializable
here code snippets
#models.py import uuid django.contrib.gis.db import models django.contrib.gis.db.models.functions import distance django.contrib.gis.geos import point class placemanager(models.geomanager): def get_queryset(self): qs = super(placemanager, self).get_queryset() qs = qs.annotate( latitude=models.expressionwrapper(models.func('position', function='st_x'), output_field=models.floatfield()), longitude=models.expressionwrapper(models.func('position', function='st_y'), output_field=models.floatfield()), ) return qs.distinct() def nearby_places(self, lat, lng): p = point(lat, lng, srid=4326) qs = self.get_queryset() qs = qs.annotate( distance=distance('position', p) ) return qs.order_by('distance').distinct() class place(models.model): id = models.uuidfield(default=uuid.uuid4, editable=false, primary_key=true, db_index=true) position = models.pointfield() address = models.textfield(default=none, null=true, blank=true) objects = placemanager() def __str__(self): return '{},{}'.format(self.position.x, self.position.y)
now code snippets have this
from rest_framework.views import apiview rest_framework import status rest_framework.response import response class nearbyplaces(apiview): def get(self, request): p = place.objects.nearby_places(30.45, -90.43) p = p.values('distance', 'address', 'latitude', 'longitude') return response(p, status=status.http_200_ok)
the value of p
here this
<geoqueryset [{'distance': distance(m=7596021.71574835), 'address': 'new york city, new york','latitude': 13.4586, 'longitude': 45.6789}]>
so needed here 'distance': 7596021.71574835
instead of 'distance': distance(m=7596021.71574835)
any on this? in advance.
just found way it. had make renderer class in rest framework , handled distance
objects in there. code snippets this.
encoders.py
from rest_framework.utils.encoders import jsonencoder django.contrib.gis.measure import distance class customjsonencoderwithdistance(jsonencoder): def default(self, obj): if isinstance(obj, distance): print(obj) return obj.m return super(customjsonencoderwithdistance, self).default(obj)
renders.py
from rest_framework.renderers import jsonrenderer .encoders import customjsonencoderwithdistance class customjsonrenderer(jsonrenderer): encoder_class = customjsonencoderwithdistance
settings.py
... rest_framework = { 'default_renderer_classes': ( 'app.renderers.customjsonrenderer', ) }
Comments
Post a Comment