如何在REST响应中获取距离字段?

时间:2017-03-27 10:04:05

标签: django django-rest-framework geodjango django-1.8

我使用GeoDjango GIS进行基于纬度和经度的邻近搜索结果。

模特,很安静简单:

class Address(gismodels.Model):
    # partner = models.ForeignKey(Partner, related_name="partner_addresses", on_delete=models.CASCADE)
    street = gismodels.CharField(max_length=255)
    city = gismodels.CharField(max_length=255)
    postcode = gismodels.CharField(max_length=255, null=True, blank=True, default='0000')
    country = gismodels.CharField(max_length=255)
    businesses = gismodels.OneToOneField(Business, related_name="business_address", on_delete=models.CASCADE, null=True)
    latitude = gismodels.FloatField(null=True, blank=True)
    longitude = gismodels.FloatField(null=True, blank=True)
    location = gismodels.PointField(null=True, blank=True)

    objects = gismodels.GeoManager()

    def __unicode__(self):
        return self.street

    class Meta:
        verbose_name = "Address"
        verbose_name_plural = "Addresses"

    def save(self, *args, **kwargs):
        if self.latitude and self.longitude:
            self.location = Point(self.longitude, self.latitude)

        super(Address, self).save(*args, **kwargs)

而且,序列化器也是如此:

class AddressSerializer(HyperlinkedModelSerializer):
    name_of_business = serializers.CharField(source="businesses.name_of_business")
    business_id = serializers.IntegerField(source="businesses.pk")
    opening_time = serializers.TimeField(source="businesses.business_details.opening_time")

    class Meta:
        model = Address
        fields = ('pk', 'distance', 'street', 'city', 'postcode',
                  'name_of_business', "business_id",
                  'opening_time')

所以,当我尝试获得回复时,请说使用curl http://127.0.0.1:5000/api/businesses/37.4418834/-122.14301949999998/,我得到与距离字段相关的错误:

Traceback (most recent call last):
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/whitenoise/base.py", line 66, in __call__
    return self.application(environ, start_response)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
    response = self.get_response(request)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/core/handlers/base.py", line 261, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response
    six.reraise(exc_type, exc_value, tb)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
    response = self.handle_exception(exc)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/dff/.virtualenvs/dff/lib/python2.7/site-packages/rest_framework/views.py", line 448, in raise_uncaught_exception
    raise exc
ImproperlyConfigured: Field name `distance` is not valid for model `Address`.

这是我的api观点:

class ProximityFilter(ListAPIView):
    serializer_class = AddressSerializer

    def get_queryset(self):
        longitude = self.kwargs.get('longitude')
        latitude = self.kwargs.get('latitude')
        current_point = GEOSGeometry('POINT(%s %s)' % (longitude, latitude), srid=4326)
        queryset = Address.objects.filter(city="SomeCity",location__distance_lte=(current_point, D(mi=700000000))).distance(
            current_point).order_by('distance')
        return queryset

如何通过REST响应来解决这个问题呢? 请问有什么线索吗?任何人? :)

由于

我正在使用Django 1.8。

1 个答案:

答案 0 :(得分:2)

这里的问题是您尝试根据名为distance的不存在的字段对查询集进行排序。您应该首先使用Distance()函数对它们进行注释:

from django.contrib.gis.db.models.functions import Distance
Address.objects.filter(...).annotate(distance=Distance("location", current_point).order_by("distance")