โ† Django-Oscar - Search Engine Whoosh - Part 2.5

Django Oscar 4 requires us to configure a search engine. For this, we use Haystack.
Search engines allow us to index and search products efficiently, enabling things like ordering alphabetically, by price, or by date added etc.



 

๐ŸŸข Basic   Simple Engine             Just testing, very few products
๐ŸŸก Intermediate           Whoosh Up to ~5,000 products, no complex search features
๐ŸŸ  Advanced Solr Over 10,000 products, robust search capabilities
๐Ÿ”ด Professional Elasticsearch Large catalogs, high performance, relevance-based search needs




Whoosh
 

 


Forcing products to be listed in the dashboard


mysite/templates/oscar/dashboard/catalogue/product_list.html

Remove lines:
67 {% if has_products %}
87 {% else %}
88 <p>{% trans "No products found." %}</p>   
89 {% endif %}
 


Automating index rebuild with Whoosh

Whoosh by default will require us to either run
python manage.py rebuild_index
or
python manage.py update_index

For a Store administrator this is not practical.
For this reason we can automate this process by detecting the post_save for Product.
Meaning that everytime the admnistritator creates or saves a new product we will update the whoosh index.

 

default_app_config = 'Store.apps.StoreConfig'

 

from django.apps import AppConfig

class StoreConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'Store'
    def ready(self):
            import Store.signals

 

import threading
from django.db.models.signals import post_save
from django.dispatch import receiver
from oscar.apps.catalogue.models import Product
from haystack import connections

@receiver(post_save, sender=Product)
def update_index_on_save(sender, instance, **kwargs):
    def do_index():
        unified_index = connections['default'].get_unified_index()
        index = unified_index.get_index(Product)
        index.update_object(instance)

    threading.Timer(0.5, do_index).start()