如何将GeoQuerySet.distance(geom,** kwargs)从Django 1.8传输到Django 3.0?

问题描述 投票:0回答:1

我在Django 1.8文档中找到了这个示例。对于我来说,遵循相同的步骤非常重要,但在Django 3.0(或2.2)中。

class AustraliaCity(NamedModel):
    point = models.PointField()
    radius = models.IntegerField(default=10000)
    allowed_distance = models.FloatField(default=0.5)
pnt = AustraliaCity.objects.get(name='Hobart').point
for city in AustraliaCity.objects.distance(pnt): print(city.name, city.distance)

但是AustraliaCity.objects.distance(pnt)在Django 3.0中导致错误。 AttributeError:“ AustraliaCity”对象没有属性“ distance”。

Traceback (most recent call last):
  File "/home/PycharmProjects/my_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/PycharmProjects/my_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/PycharmProjects/my_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/PycharmProjects/my_project/my_project/web.py", line 21, in show
    print(city.name, city.distance)
AttributeError: 'AustraliaCity' object has no attribute 'distance'

我将不胜感激。

django geodjango django-1.8 django-2.2 django-3.0
1个回答
0
投票

您应该可以使用批注进行此操作

from django.contrib.gis.db.models.functions import Distance
for city in AustraliaCity.annotate(distance=D('point', pnt):
    print(city.name, city.distance)
© www.soinside.com 2019 - 2024. All rights reserved.