I am trying to implement a proximity search based on latitude and longitude using Django and Postgresql. Here's the abstract version of the Model I have.
class Item(models.Model):
"""docstring for Item"""
uuid = UUIDField(primary_key=True, auto=True)
name = models.CharField(_("name"), max_length=200)
address = models.CharField(_('street address'), max_length=255, blank=True, null=True)
location = models.CharField(_('location'), max_length=40, blank=True, null=True)
@property
def geo_distance(self, location=None):
if location is not None:
cursor = connection.cursor()
cursor.execute("SELECT geo_distance(CAST('%s')) AS POINT, CAST('%s') AS POINT)" %
self.location, location)
return round(float(cursor.fetchone() * 1.621371192237), 2)
I want to be able to do something like this in views.py:
items = Item.objects.filter(name__istartwith="Anything")
results = []
for item in items:
results.append({
'name': item.name,
'distance': item.geo_distance("(11.23123, -12.123213)")
})
I realize that this is not the best approach. Any suggestions welcome.