Skip to content

Commit 861b1e8

Browse files
q-caronPLNech
authored andcommitted
fix(tags): callable tags called only once (#231)
If a callable is used, it should be called for each and every instance as the result is supposed to vary between class instances. An Algolia index has a `tags` class attribute (common to all instances). It should not be redefined in the index model code through an instance (see ``models.AlgoliaIndex.get_raw_record``) because modifying a class attribute will have an impact on all instances (this is the difference between defining attributes in the class body and in the dunder __init__ method). See thread here: #228
1 parent f7d01f7 commit 861b1e8

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

algoliasearch_django/models.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,9 @@ def get_raw_record(self, instance, update_fields=None):
217217

218218
if self.tags:
219219
if callable(self.tags):
220-
self.tags = self.tags(instance)
221-
if not isinstance(self.tags, list):
222-
self.tags = list(self.tags)
223-
tmp['_tags'] = self.tags
220+
tmp['_tags'] = self.tags(instance)
221+
if not isinstance(tmp['_tags'], list):
222+
tmp['_tags'] = list(tmp['_tags'])
224223

225224
logger.debug('BUILD %s FROM %s', tmp['objectID'], self.model)
226225
return tmp

tests/test_index.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ def setUp(self):
1515
bio='Milliseconds matter', followers_count=42001,
1616
following_count=42, _lat=123, _lng=-42.24,
1717
_permissions='read,write,admin')
18+
19+
self.contributor = User(
20+
name='Contributor',
21+
username="contributor",
22+
bio='Contributions matter',
23+
followers_count=7,
24+
following_count=5,
25+
_lat=52.0705,
26+
_lng=-4.3007,
27+
_permissions='contribute,follow'
28+
)
29+
1830
self.example = Example(uid=4,
1931
name='SuperK',
2032
address='Finland',
@@ -163,9 +175,14 @@ class UserIndex(AlgoliaIndex):
163175
tags = 'permissions'
164176

165177
index = UserIndex(User, self.client, settings.ALGOLIA)
178+
179+
# Test the users' tag individually
166180
obj = index.get_raw_record(self.user)
167181
self.assertListEqual(obj['_tags'], ['read', 'write', 'admin'])
168182

183+
obj = index.get_raw_record(self.contributor)
184+
self.assertListEqual(obj['_tags'], ['contribute', 'follow'])
185+
169186
def test_invalid_tags(self):
170187
class UserIndex(AlgoliaIndex):
171188
tags = 'tags'

0 commit comments

Comments
 (0)