Query annotation by distance to find closest distance in Django 1.11 with postgis appears incorrect

Viewed 158

Here is my model:

class Coast(TimeStampedModel):
    position = PointField(null=True, srid=4326)
    shape_id = models.IntegerField(null=True)
    state = models.CharField(max_length=4, null=True, blank=True, choices=US_STATES)
    point_type = models.CharField(max_length=25, choices=cc.POINT_TYPES, default=cc.POINT_TYPES.COAST, db_index=True)
    interpolated = models.BooleanField(default=False)

Here is the code I am running:

def get_distances(current_address):
    return (models.Coast.objects
        .filter(point_type='COAST', position__distance_lte=(current_address, D(m=10000)))
        .annotate(distance=Distance("position", current_address))
        .order_by("distance"))

current_address = Point(x=26.3960373, y=-80.0755588, srid=4326)
distances = get_distances(current_address)
for dd in distances[0:10]:
    print 'distance:', dd.distance.m, current_address.distance(dd.position)

Here is the output:

distance: 1090.96923342 2.9609226587
distance: 1091.50068042 1.80716304192
distance: 1120.14014531 1.31372843777
distance: 1129.40394238 3.86868793486
distance: 1153.68196704 1.1093495446
distance: 1193.25809435 5.09212206614
distance: 1217.1136617 1.16301011591
distance: 1231.50011729 5.09984181242
distance: 1251.77367236 6.0540028636
distance: 1301.92838504 6.5265317962

I am trying to figure out why filtering the queryset and ordering by distance

.order_by('distance')

returns a different order than calculating the distance between the two points manually?

current_address.distance(dd.position)

I am trying to find the nearest point to the current address.

1 Answers

need info of point class also

need to see Point.distance should be a function?

Related