21👍
✅
Let’s assume that your LocationInfo
has it’s geometry field named position
:
For Django version >= 1.9:
You can use the Distance()
function:
from django.contrib.gis.db.models.functions import Distance
LocationInfo.objects.annotate(
distance=Distance('position', user_location)
).order_by('distance').first()
Which will return the nearest object to the user_location
For Django 1.6 <= version < 1.9:
You can use the .distance()
method:
LocationInfo.objects.distance(user_location).order_by('distance').first()
For Django version < 1.6:
The .first()
method does not exist so you have to get the first of the ordered queryset as follows:
LocationInfo.objects.distance(user_location).order_by('distance')[:1].get()
0👍
This will give you the nearest location info:
LocationInfo.geo_objects.distance(user_location).order_by('distance')[0]
where geo_objects is Model manager for LocationInfo
from django.contrib.gis.db import models as gis_models
class LocationInfo(models.Model):
geo_objects = gis_models.GeoManager()
- Save the related objects before the actual object being edited on django admin
- No connection could be made because the target machine actively refused it (Django)
- How to give initial value in modelform
- Django select related in raw request
Source:stackexchange.com