Login

haystack auto update (forget about update_index)

Author:
jpic
Posted:
January 17, 2012
Language:
Python
Version:
1.3
Score:
-1 (after 1 ratings)

Dead simple snippet. Paste it in some models (i use project_specific/models.py), and you don't need to run update_index anymore. When a model is deleted from the database: it is deleted from the index. When a model is saved (created or modified): it is updated in the index.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from haystack.sites import site
from django.db.models import signals

def add_to_search_index(sender, instance=None, **kwargs):
    try:
        index = site.get_index(instance.__class__)
    except:
        return
    
    index.backend.update(index, [instance])
signals.post_save.connect(add_to_search_index)

def delete_from_search_index(sender, instance=None, **kwargs):
    try:
        index = site.get_index(instance.__class__)
    except:
        return
    
    index.backend.remove(instance)
signals.post_delete.connect(delete_from_search_index)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

jpic (on January 17, 2012):

Don't use this snippet. Use RealTimeSearchIndex instead of SearchIndex.

#

Please login first before commenting.