我有以下这个模型。
class Location(models.Model):
name = models.CharField(max_length = 128, blank = True)
address =models.CharField(max_length = 200, blank= True)
latitude = models.DecimalField(max_digits=6, decimal_places=3)
longitude = models.DecimalField(max_digits=6, decimal_places=3)
def __unicode__(self):
return self.name
如果我的当前纬度和经度是:
current_lat = 43.648
current_long = 79.404
我做了一些研究,发现了Haversine Equation,它可以计算两个位置坐标之间的距离。下面是我找到的公式:
import math
def distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2-lat1)
dlon = math.radians(lon2-lon1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = radius * c
return d
我想要返回所有在10公里半径范围内的位置对象,如何进行筛选以便只返回这个10公里半径范围内的所有位置对象?
LocationsNearMe = Location.objects.filter(#This is where I am stuck)
有没有办法将Haversine方程式应用于过滤中,以便它仅返回在10公里半径范围内的位置对象?
我正在寻找详细的答案。感谢帮助。