@@ -25,7 +25,7 @@ class AlgoliaIndex(object):
25
25
fields = ()
26
26
27
27
# Use to specify the geo-fields that should be used for location search.
28
- # The field should be a callable that returns a tuple.
28
+ # The attribute should be a callable that returns a tuple.
29
29
geo_field = None
30
30
31
31
# Use to specify the field that should be used for filtering by tag.
@@ -37,6 +37,10 @@ class AlgoliaIndex(object):
37
37
# Use to specify the settings of the index.
38
38
settings = {}
39
39
40
+ # Use to specify a callable that say if the instance should be indexed.
41
+ # The attribute should be a callable that returns a booleen.
42
+ should_index = None
43
+
40
44
# Instance of the index from algoliasearch client
41
45
__index = None
42
46
@@ -87,6 +91,16 @@ def __init__(self, model, client):
87
91
raise AlgoliaIndexError ('{} is not an attribute of {}.' .format (
88
92
self .geo_field , model ))
89
93
94
+ if self .should_index :
95
+ if hasattr (model , self .should_index ):
96
+ attr = getattr (model , self .should_index )
97
+ if not callable (attr ):
98
+ raise AlgoliaIndexError ('{} should be a callable.' .format (
99
+ self .should_index ))
100
+ else :
101
+ raise AlgoliaIndexError ('{} is not an attribute of {}.' .format (
102
+ self .should_index , model ))
103
+
90
104
def __set_index (self , client ):
91
105
'''Get an instance of Algolia Index'''
92
106
params = getattr (settings , 'ALGOLIA' , None )
@@ -154,6 +168,15 @@ def _build_object(self, instance):
154
168
155
169
def update_obj_index (self , instance ):
156
170
'''Update the object.'''
171
+ if self .should_index :
172
+ attr = getattr (instance , self .should_index )
173
+ if not attr ():
174
+ # Should not index, but since we don't now the state of the
175
+ # instance, we need to send a DELETE request to ensure that if
176
+ # the instance was previously indexed, it will be removed.
177
+ self .delete_obj_index (self , instance )
178
+ return
179
+
157
180
obj = self ._build_object (instance )
158
181
self .__index .save_object (obj )
159
182
logger .debug ('UPDATE %s FROM %s' , obj ['objectID' ], self .model )
@@ -187,6 +210,11 @@ def reindex_all(self, batch_size=1000):
187
210
counts = 0
188
211
batch = []
189
212
for instance in self .model .objects .all ():
213
+ if self .should_index :
214
+ attr = getattr (instance , self .should_index )
215
+ if not attr ():
216
+ continue # should not index
217
+
190
218
batch .append (self ._build_object (instance ))
191
219
if len (batch ) >= batch_size :
192
220
result = self .__tmp_index .save_objects (batch )
0 commit comments