将 SearchVectorField 添加到 Django 中的模型

BWr*_*tes 6 python django postgresql django-models django-postgresql

所以我正在尝试将SearchVectorField添加到 Django 中的模型中:

class JobPosting(models.Model):
    ...
    ...
    search_vector = SearchVectorField()
Run Code Online (Sandbox Code Playgroud)

我知道它应该是nullable或具有默认值才能迁移,因此我删除了表中的所有条目以防止出现此问题。

但是,运行时出现以下错误makemigrations

You are trying to add a non-`nullable` field 'search_vector' to jobposting without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
   1) Provide a one-off default now
      (will be set on all existing rows with a null value for this column)
   2) Quit, and let me add a default in models.py
Select an option:
Run Code Online (Sandbox Code Playgroud)

如果桌子是空的,为什么会这样说?我不想使列可以为空,如果可以避免,我宁愿没有默认值。

我的问题是,如果表是空的,有没有办法强制makemigrationsmigrate因为我不明白这个问题。我还有其他包含数据的表,我不想删除这些数据,因此无法删除数据库中的所有信息。

或者,如果选项1)是解决方案,我将如何格式化此类字段的默认值?我认为它不是一个普通的文本字段?

谢谢你的帮助。

Ste*_*ögl 8

我不完全确定为什么你不想有一个默认值,但我会假设这是给定的。

我的问题是,有没有办法强制 makemigrations 和迁移,因为如果表是空的,我不明白这个问题。

当前的数据库表可能是空的,但迁移应该可以在其他数据库实例上重复。因此 Django 不能假设在任何其他数据库上也是如此。

解决方法可能是定义一个迁移,将字段创建为可为空的,索引所有条目,然后将其更新为不可为空。

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib.postgres.search import SearchVector, SearchVectorField      
from django.db import migrations


def index_entries(apps, schema_editor):
    Entry = apps.get_model("mymodel", "Entry")
    Entry.objects.update(search_vector=SearchVector('body_text'))


class Migration(migrations.Migration):

    dependencies = [
        ('mymodel', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='entry',
            name='search_vector',
            field=SearchVectorField(null=True),
        ),

        migrations.RunPython(index_entries),

        migrations.AlterField(
            model_name='entry',
            name='search_vector',
            field=SearchVectorField(null=False),
        ),
    ]
Run Code Online (Sandbox Code Playgroud)