是否可以在Django的SearchVectorField中保留一个联接字段? [英] Is it possible to persist a joined field in Djangos SearchVectorField?

查看:71
本文介绍了是否可以在Django的SearchVectorField中保留一个联接字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Django的SearchVectorField保留连接字段以进行全文搜索?

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

例如:

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

代码:

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

引发此异常:

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?

推荐答案

我找到了解决您问题的方法:

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()

更新2018-06-29

如官方文档中所述


如果您只是更新记录,而无需对模型对象做任何事情,那是最有效的方法

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.

使用update()还可以防止出现竞争情况,因为这种情况可能会在短期内改变数据库中的某些内容

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().

最后,意识到update()在SQL级别进行更新,因此不调用任何方法。 save()米模式上的模式,也不会发出pre_save或post_save信号(这是调用Model.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()).

因此,在这种情况下,您可以使用此查询对数据库执行单个SQL查询:

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')
)

这篇关于是否可以在Django的SearchVectorField中保留一个联接字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆