15
15
# from django.contrib.postgres.search import SearchVector
16
16
# GinIndex(fields=[SearchVector("description", config="english")])
17
17
# see https://code.djangoproject.com/ticket/26167
18
+ # this is a hack inspired by this blog post:
19
+ # https://vxlabs.com/2018/01/31/creating-a-django-migration-for-a-gist-gin-index-with-a-special-index-operator/
18
20
class SearchVectorIndex (GinIndex ):
19
21
def __init__ (self , config = "english" , * args , ** kwargs ):
20
22
self .config = config
21
23
super ().__init__ (* args , ** kwargs )
22
24
23
- def get_sql_create_template_values (self , model , schema_editor , using ):
24
- fields = [model ._meta .get_field (field_name ) for field_name , order in self .fields_orders ]
25
- tablespace_sql = schema_editor ._get_index_tablespace_sql (model , fields )
26
- quote_name = schema_editor .quote_name
27
- columns = [
28
- ("to_tsvector('%s', %s) %s" % (self .config , quote_name (field .column ), order )).strip ()
29
- for field , (field_name , order ) in zip (fields , self .fields_orders )
30
- ]
31
- return {
32
- 'table' : quote_name (model ._meta .db_table ),
33
- 'name' : quote_name (self .name ),
34
- 'columns' : ', ' .join (columns ),
35
- 'using' : using ,
36
- 'extra' : tablespace_sql ,
37
- }
25
+ def create_sql (self , model , schema_editor , ** kwargs ):
26
+ statement = super ().create_sql (model , schema_editor , ** kwargs )
27
+ # this works only for one column, otherwise we get a list inside to_tsvector
28
+ statement .template = "CREATE INDEX %(name)s ON %(table)s%(using)s (to_tsvector('" + self .config + "'::regconfig, %(columns)s))%(extra)s"
29
+ return statement
38
30
39
31
class Package (models .Model ):
40
32
id = models .AutoField (primary_key = True )
@@ -55,7 +47,7 @@ class Meta:
55
47
)
56
48
indexes = (
57
49
GinIndex (name = "package_name" , fields = ["name" ], opclasses = ["gin_trgm_ops" ]),
58
- SearchVectorIndex (fields = ["description" ], config = "english" ),
50
+ SearchVectorIndex (name = "package_description_search" , fields = ["description" ], config = "english" ),
59
51
)
60
52
61
53
def __str__ (self ):
0 commit comments