如何追溯创建不破坏 django-admin 的自动字段?

发布于 2024-09-10 12:52:37 字数 542 浏览 1 评论 0原文

我在 Django 应用程序中使用 manage.pyspectdb 在 现有的 postgres 数据库。这似乎有效,除了所有 主键在模型中被描述为 IntegerField ,这使得 它们可以在管理面板中编辑,并且必须根据 了解先前记录的 id。我刚刚了解到这个 在客户使用了一些之后,所以我回去更改诸如

blog_id = models.IntegerField(primary_key=True)

...之类的内容...

blog_id = models.AutoField(primary_key=True)

现在 id 字段不会出现在管理面板中(很好),但是添加新行 已经变得不可能了(不好)。

/admin/franklins_app/blog/add/ 处出现完整性错误

重复的键值违反了唯一约束“blog_pkey”

解决方法是什么? (额外问题:是否可以捕获 Django 尝试分配为新行主键的值?)

I created the models in a Django app using manage.py inspectdb on an
existing postgres database. This seemed to work except that all the
primary keys were described in the models as IntegerFields, which made
them editable in the admin panel, and had to be hand-entered based on
knowledge of the id of the previous record. I just learned about this
after some usage by the client, so I went back to change things like

blog_id = models.IntegerField(primary_key=True)

...to...

blog_id = models.AutoField(primary_key=True)

Now the id fields don't appear in the admin panel (good), but adding new rows
has become impossible (not good).

IntegrityError at /admin/franklins_app/blog/add/

duplicate key value violates unique constraint "blog_pkey"

What's the fix? (Bonus question: is it possible to capture the value that Django is trying to assign as the primary key for the new row?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可是我不能没有你 2024-09-17 12:52:37

作为主键的序列字段后面的序列不知道手动输入的记录。

找到主键的最大值:

SELECT MAX(<primary_key>) FROM <your_table>;

然后将基础序列的下一个值设置为大于该值的数字:

SELECT SETVAL('<primary_key_seq>', <max_value_in_primary_key_plus_something_for_safety>);

您将找到序列的名称(上面提到的)使用:

SELECT pg_get_serial_sequence('<your_table_name>', '<primary_key_column_name');

The sequence behind the serial field which is your primary key doesn't know about the manually entered records.

Find the maximum value of the primary key:

SELECT MAX(<primary_key>) FROM <your_table>;

Then set the next value of the underlying sequence to a number greater than that:

SELECT SETVAL('<primary_key_seq>', <max_value_in_primary_key_plus_something_for_safety>);

You'll find the name of the sequence (mentioned above as <primary_key_seq>) using:

SELECT pg_get_serial_sequence('<your_table_name>', '<primary_key_column_name');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文