在 上一篇文章 中,介绍了数据库 sequence 出现紊乱时的处理方法。
今天才发现,原来 Django 已经提供了这个辅助工具 -- sqlsequencereset. 官网是这样介绍的:
django-admin sqlsequencereset app_label [app_label ...]
Prints the SQL statements for resetting sequences for the given app name(s).
Sequences are indexes used by some database engines to track the next available number for automatically incremented fields.
Use this command to generate SQL which will fix cases where a sequence is out of sync with its automatically incremented field data.
也就是说,只要执行 sqlsequencereset app_label
, 就能生成我们需要的重置序列的SQL指令。
例如
sqlsequencereset auth
会生成
BEGIN;
SELECT setval(pg_get_serial_sequence('"auth_permission"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_permission";
SELECT setval(pg_get_serial_sequence('"auth_group_permissions"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_group_permissions";
SELECT setval(pg_get_serial_sequence('"auth_group"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_group";
SELECT setval(pg_get_serial_sequence('"auth_user_groups"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_user_groups";
SELECT setval(pg_get_serial_sequence('"auth_user_user_permissions"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_user_user_permissions";
SELECT setval(pg_get_serial_sequence('"auth_user"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "auth_user";
COMMIT;
然后在数据库管理工具中,复制上述指令,就能重置序列了。