---
slug: "Django1.7で、マイグレーションファイルでフルテキストインデックスを作成する"
title: "Create a Full-Text Index in Migration Files with Django 1.7"
description: "\n\nThis is a method to create a full-text index in MySQL using the DB migration feature in Django 1.7 and above."
url: "https://www.ytyng.com/en/blog/Django1.7で、マイグレーションファイルでフルテキストインデックスを作成する"
publish_date: "2015-09-03T11:48:31Z"
created: "2015-09-03T11:48:31Z"
updated: "2026-02-27T10:43:00.486Z"
categories: ["Django"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/0794c321efb2452d9a07585ebe0c707c.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# Create a Full-Text Index in Migration Files with Django 1.7

<div class="document">

<p>This is a method to create a full-text index in MySQL using the DB migration feature in Django 1.7 and above.</p>
<p>By the way, MySQL 5.6 and above allows you to create full-text indexes in InnoDB as well.</p>
<p>First, you need to install the sqlparse module.</p>
<pre class="literal-block">$ pip install sqlparse
</pre>
<p>In advance, create a text field in your model for applying the full-text index.</p>
<pre class="literal-block">class HogeSearch(models.Model):
    ...
    search_text = models.TextField(default='', blank=True)
</pre>
<p>Then, generate a normal migration file first.</p>
<pre class="literal-block">$ ./manage.py makemigrations hogeapp
</pre>
<p>Next, create an empty migration file.</p>
<pre class="literal-block">$ ./manage.py makemigrations hogeapp --empty
</pre>
<p>When you look at the created migration file, you will see a list called operations. Insert a migrations.RunSQL instance into this list.</p>
<pre class="literal-block"># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

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

    operations = [
        migrations.RunSQL(
            "CREATE FULLTEXT INDEX i_search_text ON hogeapp_hogemodel (search_text)",
            "DROP INDEX i_search_text ON hogeapp_hogemodel"),
    ]
</pre>
<p>The second argument of migrations.RunSQL is SQL for reverse migration, so it is not mandatory.
(However, if it is not provided, attempting reverse migration (e.g., ./manage.py migrate hogeapp 0001) will cause a Migration.IrreversibleError exception and fail.)</p>
<p>When you execute the created migration, the full-text index will be applied.</p>
<pre class="literal-block">$ ./manage.py migrate hogeapp
</pre>
</div>
