问题
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?
回答1:
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'))
...
回答2:
SearchVector should not be used like this. It should be ONLY accept field name.
Please look here
来源:https://stackoverflow.com/questions/42679743/is-it-possible-to-add-your-own-strings-to-a-django-searchvectorfield