2011-03-28 103 views
19

我需要添加一個FULLTEXT索引到我的Django模型的字段之一,並明白沒有內置的功能來做到這一點,這樣的索引必須手動添加到MySQL(我們的後面結束DB)。Django南遷移 - 添加FULLTEXT索引

我想要在每個環境中創建此索引。我知道模型更改可以用Django南遷移來處理,但是有沒有辦法將這樣的FULLTEXT索引作爲遷移的一部分來添加?

通常,如果有任何需要運行的自定義SQL,我如何才能使其成爲遷移的一部分。

謝謝。

回答

31

你可以寫任何東西作爲遷移。這纔是重點!

啓動並運行South後,請輸入python manage.py schemamigration myapp --empty my_custom_migration以創建可自定義的空白遷移。

myapp/migrations/中打開XXXX_my_custom_migration.py文件,然後在forwards方法中鍵入您的自定義SQL遷移。例如,你可以使用db.execute

遷移可能是這個樣子:

class Migration(SchemaMigration): 

    def forwards(self, orm): 
     db.execute("CREATE FULLTEXT INDEX foo ON bar (foobar)") 
     print "Just created a fulltext index..." 
     print "And calculated {answer}".format(answer=40+2) 


    def backwards(self, orm): 
     raise RuntimeError("Cannot reverse this migration.") 
     # or what have you 


$ python manage.py migrate myapp XXXX # or just python manage.py migrate. 
"Just created fulltext index...." 
"And calculated 42"