I am using
- python 2.7.12
- django 1.10.6
- postgreSQL 9.5.6
- postGIS 2.2.2
First question
I need to use GeoDjango to calculate distance between two points. When I checked the documentation it says that GeoQuerySet.distance() is deprecated and instead use Distance() from django.contrib.gis.db.models.functions.
The following code works OK:
from django.contrib.gis.db.models.functions import Distance
p1 = Instrument.objects.get(pk=151071000).coordinates
p2 = Instrument.objects.filter(pk=151071008)
for i in p2.annotate(distance=Distance('coordinates', p1)):
print i.distance
print i.distance.__class__
Output:
461.10913945 m
<class 'django.contrib.gis.measure.Distance'>
My model:
class Instrument(models.Model):
...
coordinates = gis_models.PointField(null=True, blank=True, dim=3)
But I have only two points so when I try to use Distance() without annotate() it returns instance of class django.contrib.gis.db.models.functions.Distance() rathen than django.contrib.gis.measure.Distance():
p1 = Instrument.objects.get(pk=151071000).coordinates
p2 = Instrument.objects.get(pk=151071008).coordinates
print Distance(p1, p2)
Output:
Distance(Value(SRID=4326;POINT Z (-76.48623600000001 44.260223 0)), GeomValue(SRID=4326;POINT Z (-76.490923 44.262658 0)))
How do I receive the same result as with using annotate()?
Second question
I have to calculate 3d distance that is taking into account depth/elevation. But when I try to do it I receive the same result as with 2d. Below I changed elevation to 200 in the first object:
p1 = Instrument.objects.get(pk=151071000)
p1.coordinates = 'SRID=4326;POINT Z (-76.48623600000001 44.260223 200)'
p2 = Instrument.objects.filter(pk=151071008)
for i in p2.annotate(distance=Distance('coordinates', p1.coordinates)):
print i.distance
Output:
461.10913945 m
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…