Django sort by distance

前端 未结 7 1008
旧时难觅i
旧时难觅i 2020-11-28 04:34

I have the following model:

class Vacancy(models.Model):
    lat = models.FloatField(\'Latitude\', blank=True)
    lng = models.FloatField(\'Longitude\', bla         


        
7条回答
  •  时光取名叫无心
    2020-11-28 05:17

    If you don't want/have no opportunity to use gis, here is sollution (haversine distance fomula writter in django orm sql):

    lat = 52.100
    lng = 21.021
    
    earth_radius=Value(6371.0, output_field=FloatField())
    
    f1=Func(F('latitude'), function='RADIANS')
    latitude2=Value(lat, output_field=FloatField())
    f2=Func(latitude2, function='RADIANS')
    
    l1=Func(F('longitude'), function='RADIANS')
    longitude2=Value(lng, output_field=FloatField())
    l2=Func(longitude2, function='RADIANS')
    
    d_lat=Func(F('latitude'), function='RADIANS') - f2
    d_lng=Func(F('longitude'), function='RADIANS') - l2
    
    sin_lat = Func(d_lat/2, function='SIN')
    cos_lat1 = Func(f1, function='COS')
    cos_lat2 = Func(f2, function='COS')
    sin_lng = Func(d_lng/2, function='SIN')
    
    a = Func(sin_lat, 2, function='POW') + cos_lat1 * cos_lat2 * Func(sin_lng, 2, function='POW')
    c = 2 * Func(Func(a, function='SQRT'), Func(1 - a, function='SQRT'), function='ATAN2')
    d = earth_radius * c
    
    Shop.objects.annotate(d=d).filter(d__lte=10.0)
    

    PS change models, change filter to order_by, change keyword and parametrize

    PS2 for sqlite3, you should ensure, that there are available function SIN, COS, RADIANS, ATAN2, SQRT

提交回复
热议问题