Search code examples
djangopostgresqlfull-text-searchtsvector

Django SearchVector on model IntegerField


If I have a simple model like:

class Book(models.Model):
    title = models.TextField()
    year = models.IntegerField()

How can I use SearchVector in postgres to allow for searching on both the title and year fields? E.g. so "Some Book 2018" would query over both the title and year fields.

If I try doing this like:

q = SearchQuery('Some') & SearchQuery('Book') & SearchQuery('2018')
vector = SearchVector('title') + SearchVector('year')
Book.objects.annotate(search=vector).filter(search=q)

Then I hit the error

DataError: invalid input syntax for integer: ""
LINE 1: ...|| to_tsvector(COALESCE("book_book"."year", '') || ' '...

Is there anyway I can search the Integer field too?


Solution

  • As you read in the error log you cannot use integer in a search vector, but you can easily cast your integer into a string in your query.

    You can execute this code to made your full-text search with your Book model:

    from django.contrib.postgres.search import SearchQuery, SearchVector
    from django.db.models.functions import Cast
    from django.db.models import CharField
    
    q = SearchQuery('Some') & SearchQuery('Book') & SearchQuery('2018')
    
    vector = SearchVector('headline') + SearchVector(Cast('rating', CharField()))
    
    Book.objects.annotate(search=vector).filter(search=q)