gpt4 book ai didi

python - 带距离查找的 Geodjango 查询

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:01 25 4
gpt4 key购买 nike

我想根据 geodjango 查询中计算的距离对结果进行排序。
我尝试了两种方法,但它们抛出错误。

模型.py

class Partner(models.Model):
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
location = models.PointField(u"longitude/latitude",geography=True, blank=True, null=True)

View .py

方法一:

testing = Partner.objects.filter(location__distance_lte=(pnt, D(km=40))).annotate(distance=Distance('location', pnt)).order_by('distance')
print(testing)

错误:

Internal Server Error: /partner/filter/
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/prasanna/Projects/partner_server/partner/views.py", line 79, in Filter_function
print(testing.annotate(distance=Distance('location', pnt)).order_by('distance'))
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

方法2:

testing = Partner.objects.filter(location__distance_lte=(pnt, D(km=40))).annotate(distance=Distance('location', pnt)).order_by('distance')
print(testing)

错误:

Internal Server Error: /partner/filter/
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/prasanna/Projects/partner_server/partner/views.py", line 79, in Filter_function
print(testing.distance(pnt).order_by('distance'))
AttributeError: 'QuerySet' object has no attribute 'distance'

最佳答案

您的查询是正确的,但我认为您错过了某些内容,或者您​​混合了两种类型的距离,并且第一个用法与第二个用法不同。

这是一个测量对象1- 从 django.contrib.gis.measure 导入距离

这是地理数据库函数之一2-来自 django.contrib.gis.db.models.functions 导入距离

第二个函数将以注释函数理解的比较方式迭代每个对象(数据库中的行),但是第一个函数只是一个基本测量函数,不能迭代或充当比较函数

你可以引用django文档看看区别

测量:https://docs.djangoproject.com/en/2.1/ref/contrib/gis/measure/

数据库功能:https://docs.djangoproject.com/en/2.1/ref/contrib/gis/functions/#django.contrib.gis.db.models.functions.Distance

关于python - 带距离查找的 Geodjango 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47748816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com