Skip to content

Instantly share code, notes, and snippets.

@venkatesh22
Forked from mattdennewitz/gist:2847650
Last active August 29, 2015 14:07
Show Gist options
  • Save venkatesh22/c718b06618935f3a0c29 to your computer and use it in GitHub Desktop.
Save venkatesh22/c718b06618935f3a0c29 to your computer and use it in GitHub Desktop.
from django.db.models import signals
from haystack.indexes import RealTimeSearchIndex
class ManyAwareRealTimeSearchIndex(RealTimeSearchIndex):
"""Many-to-many aware real-time search index base class
"""
def _on_m2m_changed(self, instance, using=None, **kwargs):
"""Listen for post-action changes to a many-to-many field,
and (possibly) index and object.
"""
# ignore any pre-save actions
if kwargs['action'].startswith('post_'):
self.update_object(instance, using=using, **kwargs)
def _setup_save(self, model):
signals.post_save.connect(self.update_object, sender=model)
# connect each of the model's many-to-many fields
# to the m2m change listener
for m2m in model._meta.many_to_many:
signals.m2m_changed.connect(self._on_m2m_changed,
sender=m2m.rel.through)
def _teardown_save(self, model):
signals.post_save.disconnect(self.update_object, sender=model)
# disconnect each many-to-many field from the change handler
for m2m in model._meta.many_to_many:
signals.m2m_changed.disconnect(self._on_m2m_changed,
sender=m2m.rel.through)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment