Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango Sort By Calculated Field
    primarykey
    data
    text
    <p>Using the distance logic from <a href="https://stackoverflow.com/questions/1916953/filter-zipcodes-by-proximity-in-django-with-the-haversine-formula">this SO post</a>, I'm getting back a properly-filtered set of objects with this code:</p> <pre><code>class LocationManager(models.Manager): def nearby_locations(self, latitude, longitude, radius, max_results=100, use_miles=True): if use_miles: distance_unit = 3959 else: distance_unit = 6371 from django.db import connection, transaction cursor = connection.cursor() sql = """SELECT id, (%f * acos( cos( radians(%f) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(%f) ) + sin( radians(%f) ) * sin( radians( latitude ) ) ) ) AS distance FROM locations_location HAVING distance &lt; %d ORDER BY distance LIMIT 0 , %d;""" % (distance_unit, latitude, longitude, latitude, int(radius), max_results) cursor.execute(sql) ids = [row[0] for row in cursor.fetchall()] return self.filter(id__in=ids) </code></pre> <p>The problem is I can't figure out how to keep the list/ queryset sorted by the distance value. I don't want to do this as an extra() method call for performance reasons (one query versus one query on each potential location in my database). A couple of questions:</p> <ol> <li>How can I sort my list by distance? Even taking off the native sort I've defined in my model and using "order_by()", it's still sorting by something else (id, I believe).</li> <li>Am I wrong about the performance thing and Django will optimize the query, so I should use extra() instead?</li> <li>Is this the totally wrong way to do this and I should use the geo library instead of hand-rolling this like a putz?</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload