Home > Software design >  How to specify the SearchVector content manually in Django for Postgres?
How to specify the SearchVector content manually in Django for Postgres?

Time:11-09

Django supports the Postgres full-text-search using a SearchVectorField. The data has to be prepared using to_tsvector on the Postgres side which is done by the SearchVector function in Django:

class SomeSearchableModel(PostgresModel):
    searchable = SearchVectorField()

I need to populate this column with data not stored in other columns of the table. The default way to go would be:

class SomeSearchableModel(PostgresModel):
    text = TextField()
    searchable = SearchVectorField()

On every save:

    obj.searchable=SearchVector('text') # Column name to be read

This application doesn't hold the searchable data in a usable format within the database. The content is prepared within some backend script.

How do I provide the SearchVectorField content manually?

Like:

    obj.searchable=SearchVector(some_processed_text)

The PostgreSQL query part would be: INSERT INTO ... SET searchable=to_tsvector(...).

Calculating the content in Postgres is no option.

CodePudding user response:

I think you just use the search look up.

Taken from - https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/search/#the-search-lookup

Entry.objects.filter(body_text__search='Cheese')

CodePudding user response:

The arguments to SearchVector can be any Expression or the name of a field. Multiple arguments will be concatenated together using a space so that the search document includes them all.  SearchVector(Value('some text'))

Thanks to Swen for the answer.

  • Related