Django 尝试写入生成的列

Vik*_*tor 8 django postgresql

我已将 GIN 索引添加到我的数据库中

ALTER TABLE mtn_order
ADD COLUMN textsearchable_index_col tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(descr, '') || ' ' || coalesce(descrrep, ''))) STORED;
CREATE INDEX textsearch_idx ON mtn_order USING GIN (textsearchable_index_col);
Run Code Online (Sandbox Code Playgroud)

对于textsearchable_index_col = SearchVectorField(null=True)我的模型,现在当我尝试保存新实例时,我得到:

ProgrammingError at /order/create/
cannot insert into column "textsearchable_index_col"
DETAIL:  Column "textsearchable_index_col" is a generated column.
Run Code Online (Sandbox Code Playgroud)

如何阻止 Django 尝试写入None该字段

Mat*_*kel 5

您将无法将其作为字段添加到模型中,因为 Django 会尝试将值写回其中。

当您需要时,您可以对其进行注释:

MyModel.objects.annotate(
    index_col=RawSQL('textsearchable_index_col', 
                     [], 
                     output_field=SearchVectorField()
)
Run Code Online (Sandbox Code Playgroud)