PostgreSQL为已存在的列创建生成的列

2024-09-30 08:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django迁移文件中执行以下原始SQL命令。我需要使用原始SQL,因为Django不支持生成的列

ALTER TABLE dockets_document ADD COLUMN search_vector tsvector GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(f_arr2text(content),'')), 'B') ||
    setweight(jsonb_to_tsvector('english', coalesce(tables), '["all"]'), 'C')
) STORED;

我的models.py文件具有以下字段:

search_vector = SearchVectorField(null=True)

此行触发为我生成列的迁移,然后我的自定义迁移应用SQL。自定义迁移失败,因为列已创建(具有相应的索引),因此ADD COLUMN返回错误ERROR: column "search_vector" of relation "dockets_document" already exists。我试着用ALTER COLUMN代替ADD COLUMN,但没有成功(ERROR: syntax error at or near "tsvector"

我试图从models.py文件中删除该字段,但Django不知道该字段存在,也不允许我查询该列。而且我觉得把它拿走也不对

如何将现有的null列转换为GENERATED


Tags: 文件todjangoaddsqlsearchenglishcolumn
1条回答
网友
1楼 · 发布于 2024-09-30 08:16:45

您可以执行RunSQL并将state_operation添加为documented

The state_operations argument allows you to supply operations that are equivalent to the SQL in terms of project state. For example, if you are manually creating a column, you should pass in a list containing an AddField operation here so that the autodetector still has an up-to-date state of the model

在手动生成的empty迁移中

相关问题 更多 >

    热门问题