Django ORM 误读 PostgreSQL 序列?
背景:为 Django 应用程序运行 PostgreSQL 数据库(Django 1.1.1、Python2.4、psycopg2 和 Postgres 8.1) 我已经从 SQL 转储中恢复了数据库多次。每次我这样做,然后尝试添加新行(无论是 shell、管理还是站点前端)时,都会收到此错误:
IntegrityError:重复键违反了唯一约束“app_model_pkey”
数据转储是很好,正在重置序列。 但是如果我尝试再次添加该行,就会成功!因此,我可以尝试在每个表中插入一个新行,然后一切似乎都很顺利。
问题:考虑到 (1) SQL 转储良好并且 Postgres 能够正确读取它(根据 之前的问题),以及(2)Django 的 ORM 似乎没有系统性地获取下一个值失败,什么在这个具体实例中发生了什么?
Background: Running a PostgreSQL database for a Django app (Django 1.1.1, Python2.4, psycopg2 and Postgres 8.1) I've restored the database from a SQL dump several times. Each time I do that and then try to add a new row, either shell, admin, or site front end, I get this error:
IntegrityError: duplicate key violates unique constraint "app_model_pkey"
The data dump is fine and is resetting the sequences. But if I try adding the row again, it's successful! So I can just try jamming a new row into every table and then everything seems to be copacetic.
Question: Given that (1) the SQL dump is good and Postgres is reading it in correctly (per earlier question), and (2) Django's ORM does not seem to be failing systemically getting next values, what is going on in this specific instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django 不以任何方式保存或直接读取序列值。我已经解释过了。在这个问题:2088210/django-object-creation-and-postgres-sequences。
当您尝试添加行时,Postgresql 会增加序列,即使操作结果不成功(引发重复键错误),序列增量也不会回滚。因此,这就是您第二次尝试添加行时它起作用的原因。
我不知道为什么你的序列设置不正确,你能否检查转储之前和恢复之后的序列值是什么,并对表的 max() pk 执行相同的操作?也许这是 8.1 的恢复错误?我不知道。我确信的是:这不是姜戈的错。
Django doesn't hold or directly read the sequence values in any way. I've explained it f.ex. in this question: 2088210/django-object-creation-and-postgres-sequences.
Postgresql does increment the sequence when you try to add a row, even if the result of the operation is not successful (raises a duplicate key error) the sequence incrementation doesn't rollback. So, that's the reason why it works the second time you try adding a row.
I don't know why your sequences are not set properly, could you check what is the sequence value before dump and after restore, and do the same with the max() pk of the table? Maybe it's an 8.1 bug with the restore? I don't know. What I'm sure of: it's not Django's fault.
我猜你的序列已经过时了。
你可以这样解决这个问题:
I am guessing that your sequence is out of date.
You can fix that like this: