Django:将db_index添加到现有表 [英] Django: Adding db_index to existing table

查看:61
本文介绍了Django:将db_index添加到现有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django模型,在其中创建表后,我想在该字段中添加 db_index = True .

I have a Django model where I want to add a db_index=True to a field after the table was created.

我发现Django不会创建迁移,因此不会创建索引.如果该表不存在并首先创建,则Django将创建索引.

I figured out that Django doesn't create a migration, thus the index is not created. If the table is nonexistent and first created, Django creates the index.

我已阅读 Django:db_index和makemigrations ,但我想知道是否是手动创建迁移文件的好主意?

I've read Django : db_index and makemigrations, but I wonder if it's a good idea to manually create a migration file?

我正在使用MySQL.Django的最佳做法是什么?

I'm using MySQL. What's the Django best practice on this?

推荐答案

是.这是完全可以接受的,并且(有时)甚至最佳做法是使用手写迁移.甚至有一个特殊的命令可以针对这些类型的问题创建空白迁移.

Yes. It is perfectly okay and acceptable, and (sometimes) even best practice to use a hand-written migration for this. There is even a special command that creates a blank migration just for these types of issues.

python manage.py makemigrations --empty --name create_table_index 

并像在链接中发布的示例一样对其进行

And edit it just like in the example posted in your link:

class Migration(migrations.Migration):

    dependencies = [
        ('your_app', '0001_initial'), # or last mig
    ]

    operations = [
        migrations.RunSQL("CREATE INDEX idx_column ON my_table (my_column)"),
        # this format should also work for mysql
    ]    

对于对于您的应用程序而言至关重要的表,某些操作团队更喜欢手动添加索引,以便您可以更好地控制创建索引将对应用程序产生影响的时间.但这通常是团队偏好的问题

For tables that are mission-critical to your application, some ops teams prefer to add the index by hand so that you have more control over the timing of the impact that creating the index will have on the app. But that is usually a matter of team preference

这篇关于Django:将db_index添加到现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆