4

我只是在学习geo-django。我可以从一个点找出所有地方的距离。但是当我.values对带注释的字段使用方法时distance,我得到了

TypeError: Object of type 'Distance' is not JSON serializable

这是我的代码片段

#models.py
import uuid
from django.contrib.gis.db import models
from django.contrib.gis.db.models.functions import Distance
from 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)

现在我的代码片段是这样的

from rest_framework.views import APIView
from rest_framework import status
from 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)

这里的值p是这样的

<GeoQuerySet [{'distance': Distance(m=7596021.71574835), 'address': 'New York City, New York','latitude': 13.4586, 'longitude': 45.6789}]>

所以我在这里需要的'distance': 7596021.71574835只是'distance': Distance(m=7596021.71574835)

对此有什么帮助吗?提前致谢。

4

2 回答 2

8

还有一种更简单的方法,只需要更改serializer.py中的内容即可:

class CitySerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField()

    def get_distance(self, obj):

        return obj.distance.m

    class Meta:
        model = City
        fields = ('distance')
于 2018-11-14T19:15:22.887 回答
2

刚刚找到了一种方法。必须在 rest 框架中创建一个 Renderer 类并Distance在那里处理对象。代码片段是这样的。

编码器.py

from rest_framework.utils.encoders import JSONEncoder
from 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)

渲染.py

from rest_framework.renderers import JSONRenderer
from .encoders import CustomJsonEncoderWithDistance


class CustomJsonRenderer(JSONRenderer):
     encoder_class = CustomJsonEncoderWithDistance

设置.py

...
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'app.renderers.CustomJsonRenderer',
    )
}
于 2017-07-28T16:43:55.480 回答