修改Django AutoField起始值
我有现有的数据库,我已使用 SQLAlchemy 将其迁移到新的 PostgreSQL 数据库。
我将所有主键移至与以前相同的值。现在我有充满数据的表,但关联的序列从 1 开始。我存储了 1 到 2000 的 pk 值。
现在,当我尝试使用 Django 保存某些内容时,我有
重复的键值违反了唯一约束 关于主键。
如何修改序列起始值或避免这种情况?
我当前的解决方案是:
conn = psycopg2.connect(...)
for table_name in table_names:
cursor = conn.cursor()
cursor.execute("""
SELECT setval('%s_id_seq', (SELECT COALESCE(MAX(id),0)+1 FROM %s));
"""% (table_name, table_name))
它对我有用,但我不喜欢它。
I have and existing database, which I have migrated with SQLAlchemy to a new PostgreSQL database.
I moved all primary keys with the same values as before. Now I have tables filled with data, but the associated sequences starts from 1. I have pk values stored 1 to 2000.
Now, when I try to save something with Django, I have the
duplicate key value violates unique constraint
regarding to the Primary Key.
How can I modify the sequence start values or escape this situation?
My current solution is:
conn = psycopg2.connect(...)
for table_name in table_names:
cursor = conn.cursor()
cursor.execute("""
SELECT setval('%s_id_seq', (SELECT COALESCE(MAX(id),0)+1 FROM %s));
"""% (table_name, table_name))
It works for me, but I don't like it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 PostgreSQL 中设置/重置序列的方法
(不一定是
max(id)
)。这就是您在问题中提出的简单方法。您可以使用
setval()
将序列设置为从任意数字开始:然后是标准 SQL 方式
ALTER SEQUENCE
做同样的事情:
如果您想以默认值 1 以外的数字重新启动序列:
还有另一种方法,当您使用 截断:
隐式执行
ALTER SEQUENCE foo_id_seq RESTART;
Ways to set / reset a sequence in PostgreSQL
(not necessarily to
max(id)
).There's the simple way you have in the question. You can set the sequence to start at an arbitrary number with
setval()
:Then there's the standard SQL way with
ALTER SEQUENCE
doing the same:If you like to restart your sequences at numbers other than the default 1:
And there is another way, when you empty a table with TRUNCATE:
Implicitly executes
ALTER SEQUENCE foo_id_seq RESTART;