问题描述
我正在尝试在SearchVector中使用ArrayField,但它正在返回
I'm trying to use an ArrayField in a SearchVector but it is returning
django.db.utils.DataError: malformed array literal: ""
LINE 1: ... = to_tsvector(COALESCE("example_model"."example_arrayfield", ''))
^
DETAIL: Array value must start with "{" or dimension information.
当我查询ArrayField时,它返回一个列表,例如["a","b","c"],而在数据库中则用方括号显示,例如{a,b,c}有谁知道如何使SearchVector接受ArrayField作为纯列表?还是以某种方式将普通列表转换为柯利括号?
When I query for the ArrayField it returns a list e.g. ["a","b","c"] whereas in the database it is shown in curley brackets instead e.g.{a,b,c}Does anyone know how to get the SearchVector to accept an ArrayField as just a plain list? OR somehow convert the normal list to curley brackets?
以下是启动此代码的代码:
Here is the code that starts this:
ExampleModel.objects.update(search_document=SearchVector("example_ArrayField"))
推荐答案
我知道已经一年了,但是我通过Google偶然发现了这个问题,找不到任何可以为这个确切问题提供可接受解决方案的人,所以这是代码我正在使用.
I know it's been a year, but I stumbled on this question via Google and could not find anybody with an acceptable solution for this exact problem, so here's the code I'm using.
from django.db.models import F, Func, Value
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.search import SearchVector, SearchVectorField
class SearchableStuff(models.Model):
name = models.CharField(
_('Name'),
max_length=256,
null=False, blank=False)
tags = ArrayField(
models.CharField(max_length=50, blank=True),
verbose_name=_('Tags'),
default=list,
size=16,
blank=True)
search_vector = SearchVectorField(
_('Search vector'),
null=True)
def save(self, *args, **kwargs):
self.search_vector = \
SearchVector('name', weight='A', config='french') + \
SearchVector(
Func(F('tags'), Value(' '), function='array_to_string'),
weight='A',
config='french')
return super().save(*args, **kwargs)
-编辑-发布此解决方案几个小时后,我意识到它仅在更新记录而不插入时才起作用.这是一个更好的解决方案.
--Edit-- a few hours after posting this solution, I realized that it does only work when updating a record, but not inserting it. Here's a better solution.
def save(self, *args, **kwargs):
# Note: we use `SearchVector(Value(self.field))` instead of
# `SearchVector('field')` because the latter only works for updates,
# not when inserting new records.
self.search_vector = \
SearchVector(Value(self.name), weight='A', config='french') + \
SearchVector(
Value(' '.join(self.tags)),
weight='A',
config='french')
return super().save(*args, **kwargs)
这篇关于如何在Django中将ArrayField添加到SearchVector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!