Assume that I have the following data model:
Person(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=50)
location = models.PointField(srid=4326)
Assume also that I have an app that queries a Django backend, the only function of the app is to return a list of registered users sorted from closest to farthest in a paginated format.
Currently I have the following query in mind:
# here we are obtaining all users in ordered form
current_location = me.location
people = Person.objects.distance(current_location).order_by('distance')
# here we are obtaining the first X through pagination
start_index = a
end_index = b
people = people[a:b]
Although this works, it is not as fast as I would like.
I have worries about the speed of this query. If the table was extensive (over 1 million), wouldn't the Postgres SQL database with PostGIS have to calculate the distance between the current_location
and every location
in the database prior to sorting the subsequent 1 million rows through an order_by
operation?
Can anyone suggest a more efficient alternative method for retrieving and sorting nearby users based on distance?