How to filter a django model with latitude and longitude coordinates that fall within a certain radius

后端 未结 3 665
轮回少年
轮回少年 2021-02-06 01:39

I have the following model.

class Location(models.Model):
    name = models.CharField(max_length = 128, blank = True)
    address =models.CharField(max_length =          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 02:13

    If you don't want to use GeoDjango, then you could consider writing it out with Django's Database functions. In contrast to raw SQL, this also gives you the advantage of being able to easily append/prepend other ORM filters.

    from django.db.models.functions import Radians, Power, Sin, Cos, ATan2, Sqrt, Radians
    from django.db.models import F
    
    dlat = Radians(F('latitude') - current_lat)
    dlong = Radians(F('longitude') - current_long)
    
    a = (Power(Sin(dlat/2), 2) + Cos(Radians(current_lat)) 
        * Cos(Radians(F('latitude'))) * Power(Sin(dlong/2), 2)
    )
    
    c = 2 * ATan2(Sqrt(a), Sqrt(1-a))
    d = 6371 * c
    
    LocationsNearMe = Location.objects.annotate(distance=d).order_by('distance').filter(distance__lt=10)
    

提交回复
热议问题