PostgreSQL HStore 字段与零停机迁移
使用 Django 的 HStoreField 存储动态属性,并设计安全的数据迁移策略,避免生产环境锁表。 · 难度:入门 · +10XP
HStore 动态字段迁移
当模型需要存储不确定数量的属性时,HStore 是理想选择。但添加 HStoreField 到已有表时,PostgreSQL 需要重写整个表。本教程将展示三步迁移法:先创建扩展,再添加可为空字段,最后用批量更新填充数据。同时教授如何利用 RunSQL 与 SeparateDatabaseAndState 实现零停机迁移。
from django.contrib.postgres.fields import HStoreField
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [('myapp', '0001_initial')]
operations = [
migrations.RunSQL('CREATE EXTENSION IF NOT EXISTS hstore'),
migrations.AddField(
model_name='product',
name='attributes',
field=HStoreField(null=True, blank=True),
),
# 后续用户数据填充
]