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

- Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago

## Comments

Please login first before commenting.