django-tsearch2 / tsearch2 /

Full commit
from django.db.models.signals import post_save

from tsearch2.managers import SearchManager
from tsearch2.fields import VectorField
from tsearch2.signals import handler

__all__ = ('register',)

class AlreadyRegistered(Exception): pass

registry = []

def register(model, fields=None, config=None, tsvector_field_name='tsvector', 
                search_manager_attr='index', auto_reindex=False):
    model - Django model class
    fields - dictionary of model fields as keys and field weight as values. 
            It will be combined to postgresql tsvector field.
            Can be foreign keys with '__' syntax between fields 
            For example: {'profile__title': 'A'} 

    if model in registry:
        raise AlreadyRegistered('The model %s has already been registered.' % model.__name__)


    # set names of manager and tsvector field to the model's Options
    model._meta.search_manager_attr = search_manager_attr
    model._meta.tsvector_field_name = tsvector_field_name

    # Add tsvector field to model
    model.add_to_class(tsvector_field_name, VectorField())

    # Add a custom search manager
    SearchManager(fields, config).contribute_to_class(model, search_manager_attr)

    setattr(model, 'auto_reindex', auto_reindex)
    post_save.connect(handler, sender=model)