generate-migration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGenerate Django Database Migrations
生成Django数据库迁移文件
Commands
命令
Generate migrations automatically based on model changes:
bash
sentry django makemigrationsFor a specific app:
bash
sentry django makemigrations <app_name>Generate an empty migration (for data migrations or custom work):
bash
sentry django makemigrations <app_name> --empty根据模型变更自动生成迁移文件:
bash
sentry django makemigrations针对特定应用:
bash
sentry django makemigrations <app_name>生成空迁移文件(用于数据迁移或自定义操作):
bash
sentry django makemigrations <app_name> --emptyAfter Generating
生成迁移后
- If you added a new model, ensure it's imported in the app's
__init__.py - Review the generated migration for correctness
- Run to verify the SQL
sentry django sqlmigrate <app_name> <migration_name>
- 如果添加了新模型,请确保已在应用的中导入该模型
__init__.py - 检查生成的迁移文件是否正确
- 运行来验证对应的SQL语句
sentry django sqlmigrate <app_name> <migration_name>
Guidelines
操作指南
Adding Columns
添加列
- Use instead of
db_default=<value>for columns with defaultsdefault=<value> - Nullable columns: use
null=True - Not null columns: must have set
db_default
- 对于带默认值的列,使用而非
db_default=<value>default=<value> - 可空列:设置
null=True - 非空列:必须设置
db_default
Adding Indexes
添加索引
For large tables, set on the migration as index creation may exceed the 5s timeout.
is_post_deployment = True对于大型表,在迁移文件中设置,因为创建索引可能会超过5秒超时限制。
is_post_deployment = TrueDeleting Columns
删除列
- Make column nullable () if not already
null=True - Remove all code references
- Replace with
RemoveFieldSafeRemoveField(..., deletion_action=DeletionAction.MOVE_TO_PENDING) - Deploy, then create second migration with
SafeRemoveField(..., deletion_action=DeletionAction.DELETE)
- 如果列不是可空的,先将其设置为可空()
null=True - 移除所有代码中对该列的引用
- 将替换为
RemoveFieldSafeRemoveField(..., deletion_action=DeletionAction.MOVE_TO_PENDING) - 部署后,创建第二个迁移文件,使用
SafeRemoveField(..., deletion_action=DeletionAction.DELETE)
Deleting Tables
删除表
- Remove all code references
- Replace with
DeleteModelSafeDeleteModel(..., deletion_action=DeletionAction.MOVE_TO_PENDING) - Deploy, then create second migration with
SafeDeleteModel(..., deletion_action=DeletionAction.DELETE)
- 移除所有代码中对该表的引用
- 将替换为
DeleteModelSafeDeleteModel(..., deletion_action=DeletionAction.MOVE_TO_PENDING) - 部署后,创建第二个迁移文件,使用
SafeDeleteModel(..., deletion_action=DeletionAction.DELETE)
Renaming Columns/Tables
重命名列/表
Don't rename in Postgres. Use or to keep the old name.
db_columnMeta.db_table不要在Postgres中直接重命名。使用或来保留原有名称。
db_columnMeta.db_tableResolving Merge Conflicts
解决合并冲突
If conflicts:
migrations_lockfile.txtbash
bin/update-migration <migration_name>This renames your migration, updates dependencies, and fixes the lockfile.
如果出现冲突:
migrations_lockfile.txtbash
bin/update-migration <migration_name>该命令会重命名你的迁移文件、更新依赖关系并修复锁文件。