如何将 GeoQuerySet.distance(geom, **kwargs) 从 Django 1.8 转移到 Django 3.0?
How to transfer GeoQuerySet.distance(geom, **kwargs) from Django 1.8 to Django 3.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' 对象没有属性 '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'
如有任何建议,我将不胜感激。
你应该可以通过注释来做到这一点
from django.contrib.gis.db.models.functions import Distance
for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)):
print(city.name, city.distance)
我在 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'
如有任何建议,我将不胜感激。
你应该可以通过注释来做到这一点
from django.contrib.gis.db.models.functions import Distance
for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)):
print(city.name, city.distance)