0

我在 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”对象没有属性“距离”。

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'

我将不胜感激任何建议。

4

1 回答 1

0

您应该可以使用注释来执行此操作

from django.contrib.gis.db.models.functions import Distance
for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)):
    print(city.name, city.distance)
于 2019-12-09T19:01:08.320 回答