Search code examples
djangogeodjangodjango-1.8django-2.2django-3.0

How to transfer GeoQuerySet.distance(geom, **kwargs) from Django 1.8 to Django 3.0?


I found this example in the Django 1.8 documentation. And it’s very important for me to follow the same steps, but in Django 3.0 (or 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)

But AustraliaCity.objects.distance(pnt) causes an error in Django 3.0. AttributeError: 'AustraliaCity' object has no attribute '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'

I will be grateful for any advice.


Solution

  • You should be able to do this with an annotation

    from django.contrib.gis.db.models.functions import Distance
    for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)):
        print(city.name, city.distance)