This is a quite simple snippet to integrate postgresql trgm search in django 1.6.10
This snippet is easy to adapt to other special operators by changing the trgm_search function. This example uses the operator %%
but you could use ts_vector(fieldname) @@ to_tsquery(%s)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # tested with django 1.6.10
# 1. Activate pg_trgm
# Create an empty migration (South) and add:
def forwards(self, orm):
db.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")
db.execute("CREATE INDEX model_field_trgm_idx ON app_model USING gin (field gin_trgm_ops)")
def backwards(self, orm):
db.execute("DROP INDEX IF EXISTS model_field_trgm_idx")
# Of course, replace *app*, *model* and *field* by your application, modelname and fieldname
# 2. Add the following code in your application __init__
# -*- coding: utf-8 -*-
from django.db.backends.postgresql_psycopg2.operations import DatabaseOperations
def trgm_search(self, fieldname):
t = "{0} %% %s".format(fieldname)
return t
DatabaseOperations.fulltext_search_sql = trgm_search
# 3. Now, you can simply use:
model.objects.filter(field__search="abc")
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.