File tree Expand file tree Collapse file tree 2 files changed +44
-1
lines changed Expand file tree Collapse file tree 2 files changed +44
-1
lines changed Original file line number Diff line number Diff line change @@ -134,6 +134,31 @@ class ContactIndex(AlgoliaIndex):
134
134
geo_field = ' location'
135
135
136
136
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
+
137
162
algoliasearch.register(Contact, ContactIndex)
138
163
```
139
164
Original file line number Diff line number Diff line change @@ -136,6 +136,18 @@ def __get_objectID(self, instance):
136
136
else :
137
137
return instance .pk
138
138
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
+
139
151
def _build_object (self , instance ):
140
152
'''Build the JSON object.'''
141
153
tmp = {'objectID' : self .__get_objectID (instance )}
@@ -155,8 +167,14 @@ def _build_object(self, instance):
155
167
if self .geo_field :
156
168
loc = self .geo_field (instance )
157
169
158
- if loc :
170
+ if isinstance ( loc , tuple ) :
159
171
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
160
178
161
179
if self .tags :
162
180
attr = getattr (instance , self .tags )
You can’t perform that action at this time.
0 commit comments