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

血红的双手。 提交于 2019-12-14 03:47:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!