Skip to content

Commit f57e496

Browse files
author
m-vdb
committed
AlgoliaIndex supports multiple geolocations
1 parent df44c4c commit f57e496

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,31 @@ class ContactIndex(AlgoliaIndex):
134134
geo_field = 'location'
135135

136136

137+
algoliasearch.register(Contact, ContactIndex)
138+
```
139+
Multiple geolocations are supported, for instance:
140+
141+
```python
142+
class Location(models.Model):
143+
lat = models.FloatField()
144+
lng = models.FloatField()
145+
146+
class Contact(models.Model):
147+
name = models.CharField(max_lenght=20)
148+
locations = models.ManyToManyField('Location')
149+
150+
def geolocations(self):
151+
return [
152+
{'lat': location.lat, 'lng': location.lng}
153+
for location in self.locations.all()
154+
]
155+
156+
157+
class ContactIndex(AlgoliaIndex):
158+
fields = 'name'
159+
geo_field = 'geolocations'
160+
161+
137162
algoliasearch.register(Contact, ContactIndex)
138163
```
139164

src/models.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,18 @@ def __get_objectID(self, instance):
136136
else:
137137
return instance.pk
138138

139+
@staticmethod
140+
def _validate_geolocation(geolocation):
141+
'''
142+
Make sure we have the proper geolocation format.
143+
'''
144+
if set(geolocation) != {'lat', 'lng'}:
145+
raise AlgoliaIndexError(
146+
'Invalid geolocation format, requires "lat" and "lng" keys only got {}'.format(
147+
geolocation
148+
)
149+
)
150+
139151
def _build_object(self, instance):
140152
'''Build the JSON object.'''
141153
tmp = {'objectID': self.__get_objectID(instance)}
@@ -155,8 +167,14 @@ def _build_object(self, instance):
155167
if self.geo_field:
156168
loc = self.geo_field(instance)
157169

158-
if loc:
170+
if isinstance(loc, tuple):
159171
tmp['_geoloc'] = {'lat': loc[0], 'lng': loc[1]}
172+
elif isinstance(loc, dict):
173+
self._validate_geolocation(loc)
174+
tmp['_geoloc'] = loc
175+
elif isinstance(loc, list):
176+
[self._validate_geolocation(geo) for geo in loc]
177+
tmp['_geoloc'] = loc
160178

161179
if self.tags:
162180
attr = getattr(instance, self.tags)

0 commit comments

Comments
 (0)