我正在尝试创建一种通过位置和半径来缩小django应用程序上的帖子的方法。我尝试执行此操作的方法是:
我所做的是成功连接到API,并获得了回复,但是我必须在模板而不是模型中过滤响应。我还发现以下内容似乎是缩小半径范围内的结果所需的解决方案:
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import Distance
lat = 52.5
lng = 1.0
radius = 10
point = Point(lng, lat)
Place.objects.filter(location__distance_lt=(point, Distance(km=radius)))
我需要解决的问题,希望能对您有所帮助
过滤api响应,仅从中获取我需要的信息(组件国家/地区,几何纬度,几何lng)
收集经纬度以用于以上代码?
views.py
from posts import services
def search(request):
queryset_list = posts.objects.order_by('id')
if 'location' in request.GET:
q = request.GET['location']
locations_list = services.get_location(q)
context = {
'posts': queryset_list,
'locations_list': locations_list
}
return render(request, 'posts/search.html', context)
services.py
import requests
def get_location(location):
url = 'https://api.opencagedata.com/geocode/v1/json'
params = {'q': location, 'key': '###', 'language': 'en', 'pretty': 1}
r = requests.get(url, params=params)
locations = r.json()
return locations
答案 0 :(得分:0)
我认为您可以尝试这样(基于OpenCage提供的演示JSON响应):
import requests
from django.db.models import Q
def get_location(location):
url = 'https://api.opencagedata.com/geocode/v1/json'
params = {'q': location, 'key': '###', 'language': 'en', 'pretty': 1}
r = requests.get(url, params=params)
locations = r.json()
filter_query = Q()
radius = 10
for item in locations.get('results', []):
geo = item.get('geometry')
lat = geo.get('lat')
lng = geo.get('lng')
point = Point(lng, lat)
filter_query |= Q(location__distance_lt=(point, Distance(km=radius)))
return Place.objects.filter(filter_query)