field-option-migration.md
3.09 KB
飞书单选字段 Option 迁移模板
核心问题:PUT 更新单选字段的 options 后,所有已有记录的该字段值会变成 None。必须三步走:备份 → 更新字段 → 逐条恢复。
三步模板
# ═══════════════════════════════════════
# STEP 1: Dump all records → backup JSON
# ═══════════════════════════════════════
all_records = []
page_token = None
while True:
url = f"{BASE}/tables/{TABLE}/records?page_size=50"
if page_token: url += f"&page_token={page_token}"
r = curl_get(url)
items = data.get("data", {}).get("items") or []
for item in items:
f = item.get("fields", {})
all_records.append({
"id": item.get("record_id"),
"status": f.get("状态") or "",
})
if not data.get("data", {}).get("has_more"): break
page_token = data.get("data", {}).get("page_token")
with open("backup.json", "w") as f:
json.dump(all_records, f, ensure_ascii=False, indent=2)
# ═══════════════════════════════════════
# STEP 2: PUT field with new options
# ═══════════════════════════════════════
new_options = [
{"name": "待修复"}, {"name": "修复中"}, ...
]
field_body = json.dumps({
"field_name": "状态",
"type": 3,
"property": {"options": new_options}
})
r = curl_put(f"{BASE}/tables/{TABLE}/fields/{FIELD_ID}", field_body)
# ⚠️ 此时所有记录的该字段值已全部变成 None!
# ═══════════════════════════════════════
# STEP 3: Restore each record one by one
# ═══════════════════════════════════════
for i, rec in enumerate(all_records):
new_status = map_old_to_new(rec["status"]) # your mapping logic
put_body = json.dumps({"fields": {"状态": new_status}})
r = curl_put(f"{BASE}/tables/{TABLE}/records/{rec['id']}", put_body)
if i % 10 == 9: time.sleep(1) # rate limit: ~10 req/s
关键注意事项
- 备份是救命稻草——字段更新后所有值变 None,没有备份就无法恢复
- field_name 必须带——PUT 字段时 type + field_name 都必填,否则返回
code=99992402 - 逐条 PUT 很慢——71 条约需 30-40 秒,设置合理的 timeout
- 分类映射——用标题关键词(如
[复核失败]、[提醒])做自动分类,减少人工判断量 - 保留备份文件——至少保留到迁移验证完成
实战案例:Bug 表「已关闭」→ 三态(2026-07-11)
- 移除「已关闭」,新增「已退回」「已取消」
- 60 条已关闭记录:39 条 [复核失败] + 18 条 [提醒] → 批量改「已取消」;3 条人工判断
- 备份:
~/tmp/bug_status_backup.json - 结果:71 条 0 错误,整体耗时约 90 秒