Is it possible to persist a joined field in Djangos SearchVectorField?

丶灬走出姿态 提交于 2020-05-13 07:48:07

问题


Is it possible to persist a joined field with Djangos SearchVectorField for full text search?

For example:

class P(models.Model):
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    search_vector = SearchVectorField(null=True, blank=True)

code:

p = P.objects.get(id=1)
p.search_vector = SearchVector('brand__name')
p.save()

raises this exception:

FieldError: Joined field references are not permitted in this query

If this is not possible how can you increase the performance of joined annotated queries?


回答1:


I found a workaround to your issue:

p = P.objects.annotate(brand_name=SearchVector('brand__name')).get(id=1)
p.search_vector = p.brand_name
p.save()

Update 2018-06-29

As reported in official documentation:

If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory.

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()).

So in this case you can use this query to perform a single SQL query on the database:

from django.contrib.postgres.search import SearchVector
from django.db.models import F

P.objects.annotate(
    brand_name=SearchVector('brand__name')
).filter(
    id=1
).update(
    search_vector=F('brand_name')
)


来源:https://stackoverflow.com/questions/45863798/is-it-possible-to-persist-a-joined-field-in-djangos-searchvectorfield

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