Django 达到序列的最大值
Django reached maximum value of sequence
我是 运行 一个每天创建数百万条记录的程序,在 运行 这个程序一年多之后,我似乎已经达到了我的 postgres 数据库的 ID 限制。
我收到的错误是
django.db.utils.DataError: nextval: reached maximum value of sequence "main_records_id_seq" (2147483647)
有没有办法使用 SQL 或 django ORM 来扩展最大 ID?或者有更好的解决方案吗?
这只是PostgreSql相关的,与Django ORM无关。不幸的是,解决方案并不简单,this 是一篇很好的文章,介绍了 DB id 迁移的 4 种策略,各有利弊。
攻略总结:
- 使用 ALTER COLUMN 更改数据类型。
- 创建一个新的 table 具有相同架构但 id 类型为 bigint 并使用 INSERT INTO。
- 此策略与策略 2 非常相似,不同之处在于我们不是在一个 SQL 查询中复制数据,而是慢慢复制大块的数据
更长时间的记录。
- 向 table 添加一个 bigint 类型的新列。将 id 值复制到 id_bigint,然后将新列重命名为 id(通过
将现有 ID 重命名为 id_old).
Django 默认使用 AutoField
[Django-doc] to specify values for the primary key at the database side. An AutoField
is an IntegerField
[Django-doc],正如 Django 文档所说:
An integer. Values from -2147483648
to 2147483647
are safe in all databases supported by Django.
您可以使用 BigAutoField
[Django-doc],它将使用:
A 64-bit integer, much like an AutoField
except that it is guaranteed to fit numbers from 1
to 9223372036854775807
.
如果您的应用程序在一年内产生 2'147'483'647,您可以使用 BigAutoField
4'294'967'298 年。
因此您可以将模型定义为:
class MyModel(models.Model):
<b>id = models.BigAutoField(primary_key=True)</b>
我是 运行 一个每天创建数百万条记录的程序,在 运行 这个程序一年多之后,我似乎已经达到了我的 postgres 数据库的 ID 限制。
我收到的错误是
django.db.utils.DataError: nextval: reached maximum value of sequence "main_records_id_seq" (2147483647)
有没有办法使用 SQL 或 django ORM 来扩展最大 ID?或者有更好的解决方案吗?
这只是PostgreSql相关的,与Django ORM无关。不幸的是,解决方案并不简单,this 是一篇很好的文章,介绍了 DB id 迁移的 4 种策略,各有利弊。
攻略总结:
- 使用 ALTER COLUMN 更改数据类型。
- 创建一个新的 table 具有相同架构但 id 类型为 bigint 并使用 INSERT INTO。
- 此策略与策略 2 非常相似,不同之处在于我们不是在一个 SQL 查询中复制数据,而是慢慢复制大块的数据 更长时间的记录。
- 向 table 添加一个 bigint 类型的新列。将 id 值复制到 id_bigint,然后将新列重命名为 id(通过 将现有 ID 重命名为 id_old).
Django 默认使用 AutoField
[Django-doc] to specify values for the primary key at the database side. An AutoField
is an IntegerField
[Django-doc],正如 Django 文档所说:
An integer. Values from
-2147483648
to2147483647
are safe in all databases supported by Django.
您可以使用 BigAutoField
[Django-doc],它将使用:
A 64-bit integer, much like an
AutoField
except that it is guaranteed to fit numbers from1
to9223372036854775807
.
如果您的应用程序在一年内产生 2'147'483'647,您可以使用 BigAutoField
4'294'967'298 年。
因此您可以将模型定义为:
class MyModel(models.Model):
<b>id = models.BigAutoField(primary_key=True)</b>