2017-04-06 69 views
1
添加SearchVectorField到模型

所以我想一個SearchVectorField添加到模型在Django:在Django

class JobPosting(models.Model): 
    ... 
    ... 
    search_vector = SearchVectorField() 

我得到它的值應爲nullable或有一個默認值,以便能夠遷移,所以我刪除了表中的所有條目以防止此問題。

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: 

爲什麼這樣說,如果表是空的:

但是,運行makemigrations當我收到以下錯誤?我不想讓列可以爲空,如果我可以避免它,我寧願沒有默認值。

我的問題是,有沒有辦法強制makemigrationsmigrate,因爲我不明白問題,如果表是空的。我有其他表中的數據,我不想刪除,所以不能刪除數據庫中的所有信息。

或者,如果選項1)是解決方案,我將如何格式化此類型的字段的默認值?我認爲這不是一個正常的文本字段?

感謝您的任何幫助。

回答

1

我不完全確定你爲什麼不想有一個默認值,但我會假設這是給定的。

我的問題是,有沒有辦法強制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), 
     ), 
    ] 
0

我只是做了場可爲空(也可能是不可編輯的,因爲你不打算改變它在管理界面也通過形式):

class JobPosting(models.Model): 
    ... 
    ... 
    search_vector = SearchVectorField(null=True, editable=False) 

而且不會有移民問題。

稍後,您可以使該字段不可爲空,但沒有真正的理由這樣做,因爲您將以編程方式更新它。