Login

Closest ORM models to a latitude/longitude point

Author:
simonw
Posted:
March 24, 2021
Language:
Python
Version:
3.0
Score:
1 (after 1 ratings)

Here's how to find the 10 closest locations to a point for a model that has latitude and longitude columns, if you're not using GeoDjango.

This runs a brute force distance calculation against every row, so it should only be used on smaller tables - probably less than 100,000 rows.

For larger tables you should use GeoDjango instead.

See also my TIL about this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.db.models import F
from django.db.models.functions import ACos, Cos, Radians, Sin

locations = Location.objects.annotate(
    distance_miles = ACos(
        Cos(
            Radians(input_latitude)
        ) * Cos(
            Radians(F('latitude'))
        ) * Cos(
            Radians(F('longitude')) - Radians(input_longitude)
        ) + Sin(
            Radians(input_latitude)
        ) * Sin(Radians(F('latitude')))
    ) * 3959
).order_by('distance_miles')[:10]

More like this

  1. codigo alto nivel by MrRocklion 1 month ago
  2. Load template from specific app by Krzysiek555 1 month, 3 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 1 month, 4 weeks ago
  4. "Magic Link" Management Command by webology 7 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 7 months ago

Comments

Please login first before commenting.