GeoDjango:距离对象不可序列化 [英] GeoDjango: Distance Object is not serializable

查看:93
本文介绍了GeoDjango:距离对象不可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am just learning the geo-django. I can find out the distance of all places from a point. But when I use .values method to the annotated distance field, I am getting

TypeError:距离"类型的对象不可JSON序列化

这是我的代码段

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

现在我拥有的代码段就是这样

Now the code snippets I have is like this

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)

So all I needed here is 'distance': 7596021.71574835 instead of 'distance': Distance(m=7596021.71574835)

对此有任何帮助吗?预先感谢.

Any help on this? Thanks in advance.

推荐答案

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

there is a more simple way, only need to change content in serializer.py:

class CitySerializer(serializers.ModelSerializer):

    distance = serializers.SerializerMethodField()

    def get_distance(self, obj):

        return obj.distance.m

    class Meta:
        model = City
        fields = ('distance')

这篇关于GeoDjango:距离对象不可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆