Reputation: 2738
I am trying to make a database query that gives me 20 closest users ordered by the distance (so closest first) I am doing the follwoing
distance_mi = 100
origin = GEOSGeometry('SRID=4326;'+ 'POINT('+ str(user_profile.current_location.x)+' '+str(user_profile.current_location.y)+')')
close_users = UserProfile.objects.exclude(user = user).filter(current_location__distance_lte=(origin, D(mi=distance_mi))).distance(origin).order_by('-distance')[:20]
but this returns back 3 users (which is correct) but the first user is 0 mi away, the second is 8 mi away and the third is 0 mi away where as I am excepting the 8 mi user to be at the very end.
I am not sure what am I doing wrong in this.
Also, the UserProfile
has the following Model
class UserProfile(models.Model):
# This field is required.
user = models.OneToOneField(User)
# Other fields here
current_location = models.PointField(null = True)
seller_current_location = models.PointField(null = True)
objects = models.GeoManager()
def __unicode__(self):
return u'%s' % (self.user.get_full_name())
Upvotes: 2
Views: 167
Reputation: 49052
Since your UserProfile
contains more than one geographic field, you should specify the one you want with the field_name
argument to distance()
.
UserProfile.objects.exclude(user=user).filter(current_location__distance_lte=(origin, D(mi=distance_mi))).distance(origin, field_name='current_location').order_by('distance')[:20]
See the documentation for more details.
Upvotes: 2