gpt4 book ai didi

django - 主键值未正确递增

转载 作者:行者123 更新时间:2023-11-29 12:37:34 24 4
gpt4 key购买 nike

我有一个 Django 模型,它的 ID 开始奇怪地增加。

列的 postgres 定义(从 Django 模型生成):

id | integer | not null default nextval('billing_invoice_id_seq'::regclass)

tpg=> SELECT MAX(id) FROM billing_invoice;
max
-------
16260

然后我通过django admin创建了一条新记录:

tpg=> SELECT MAX(id) FROM billing_invoice;
max
-------
17223

tpg=> SELECT nextval('billing_invoice_id_seq');
nextval
---------
17224

然后我创建了一条新记录,它跳过了 17224 值并插入了主键 17225:

tpg=> SELECT nextval('billing_invoice_id_seq');
nextval
---------
17226

有人知道为什么会这样吗?应用程序此时不关心,因为 id 仍在递增,但在最后几个新对象中,PK 在一个插入中从 427 -> 4357 跳过,然后在 2 个对象中跳到 8378,然后在 3 个对象中跳到 97xx它跃升至 14k。

最佳答案

从序列中获取默认值的序列列从不保证无缝。它们保证唯一升序(如定义的那样)并且可以安全地同时使用
如果从序列中提取数字的事务被回滚,该数字将被销毁并且不再使用... Per documentation:

Note: Because smallserial, serial and bigserial are implemented using sequences, there may be "holes" or gaps in the sequence of values which appears in the column, even if no rows are ever deleted. A value allocated from the sequence is still "used up" even if a row containing that value is never successfully inserted into the table column. This may happen, for example, if the inserting transaction rolls back. See nextval() in Section 9.16 for details.

如果您看到像 427 -> 4357 这样的大间隙,则表示存在严重问题。其他列(或任何进程)正在从相同的序列中绘制,或者您的应用程序逻辑有问题,以某种方式燃烧了大量序列 ID。

典型的候选者是循环出错或从未提交的事务。

关于django - 主键值未正确递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25207845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com