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

2

8

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?

Salaidh answered 8/3, 2017 at 19:1 Comment(0)
S
11

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'))
    ...
Soviet answered 26/11, 2017 at 14:16 Comment(3)
Ooooh. Nice find. Will try this.Salaidh
On Django 3, I had to specify the output_type: Value('alive', output_field=models.CharField())Haskins
Used this as a starting point to keep a SearchVectorField updated in a model save() method. The problem was to use a value from a foreignkey of the model itself (the fk is category in this example), because SearchVector('category__name') gave an error on Postgres. This approach worked: SearchVector('title') + SearchVector(Value(self.category.name, output_field=models.CharField()))Cand
A
-1

SearchVector should not be used like this. It should be ONLY accept field name.

Please look here

Amie answered 5/4, 2017 at 7:2 Comment(1)
Actually SearchVectori accept other than field names. You can use expressions in SearchVector as I've wrote in my answer.Soviet

© 2022 - 2024 — McMap. All rights reserved.