class LocationManager(models.Manager):
'''
'''
def nearby_locations(self, latitude, longitude, radius):
'''
'''
cursor = connection.cursor()
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
# sqlite doesn't natively support math functions, so add them
connection.connection.create_function('acos', 1, math.acos)
connection.connection.create_function('cos', 1, math.cos)
connection.connection.create_function('radians', 1, math.radians)
connection.connection.create_function('sin', 1, math.sin)
sql = """SELECT id, (3959 * acos(cos(radians(%f)) *
cos(radians(latitude)) * cos(radians(longitude) - radians(%f)) +
sin(radians(%f)) * sin(radians(latitude))))
AS distance FROM locations_location
GROUP BY id HAVING distance < %d
ORDER BY distance ASC""" % (latitude, longitude, latitude,
int(radius))
cursor.execute(sql)
data = [(row[0], row[1]) for row in cursor.fetchall()]
ids = [i[0] for i in data]
return self.filter(id__in=ids)