Reputation: 3319
I'm trying to use Django (1.5.1) and Haystack (2.0.1) for searching objects that include geolocation information:
from django.contrib.gis.db import models as geomodels
class GeoModel(geomodels.Model):
geo_point = geomodels.PointField()
# Geographic Locator manager
objects = geomodels.GeoManager()
...
I need to filter based on the geolocation. The following query works, basically because GeoModel
is using a geomodels.GeoManager
:
from django.contrib.gis.measure import D
from django.contrib.gis.geos import Point
...
center = Point(lat, lng)
radius = D(km=100)
GeoModel.objects.all().filter(geo_point__distance_lte=(center, radius))
The problem is when I try to use Haystack to filter results based on its geolocation. I made a subclass of SearchView:
from haystack.views import SearchView
...
class MySearchView(SearchView):
def get_results(self):
center = Point(lat, lng)
radius = D(km=100)
results = super(MySearchView, self).get_results() # << OK, get all results
return results.filter(geo_point__distance_lte=(center, radius)) # << WRONG, no results
So, how can I customize Haystack views/form to filter results based on a specific location? Thanks in advance.
Upvotes: 0
Views: 638
Reputation: 5819
I'm using a very similar setup (Django 1.5.4, Haystack 2.0.0, Elasticsearch 0.90.0) and this is what I've got:
from haystack.utils.geo import D, Point
from haystack.views import SearchView
class MySearchView(SearchView):
results = super(MySearchView, self).get_results()
...
lng = -112.0739
lat = 33.4492
center = Point(lng, lat)
radius = D(mi=50)
results = results.dwithin('geo_point', center, radius)
...
return results
An important thing to keep in mind as well is the backend. According to the Haystack backend support matrix (http://django-haystack.readthedocs.org/en/latest/backend_support.html#backend-support-matrix) only Solr and Elasticsearch support spatial data.
Upvotes: 1