2011-03-28 132 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"