Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add your own strings to a Django SearchVectorField?

I know how to do this with raw PostgreSQL commands, but want to know if there is a way to do this with Django PostgreSQL search.

class Person(models.Model):
    name = models.CharField(max_length=64)
    description = models.CharField(max_length=256)
    active = models.BooleanField(default=False)
    search_vector = SearchVectorField(blank=True)

def update_search(person):
    vector = SearchVector('name') + SearchVector('description')
    if person.active:
        vector = vector + SearchVector('alive')
    person.search_vector = vector

django.core.exceptions.FieldError: Cannot resolve keyword 'alive' into field.

I tried making 'alive' a @property method, but it looks like it only wants a db field for search.

Is there a way to do this in pure Django ORM or should I go the raw SQL route?

like image 716
Dax Avatar asked Mar 08 '17 19:03

Dax


1 Answers

You can use Value() expressions to add a string to in your SearchVector as in below example:

from django.db.models import Value

    ...
    vector = vector + SearchVector(Value('alive'))
    ...
like image 156
Paolo Melchiorre Avatar answered Sep 30 '22 16:09

Paolo Melchiorre