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 2023-11-23
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')
)
Or a shorter form (suggested by @christophe31) is:
from django.contrib.postgres.search import SearchVector
P.objects.filter(id=1).update(search_vector=SearchVector('brand__name))
Both above solutions generate the same SQL code in the database.
.get(id=1)
? I'm also looking for a solution to build a search vector from a foreign relationship. – Ellon