如何追溯创建不破坏 django-admin 的自动字段?
我在 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 IntegerField
s, 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为主键的序列字段后面的序列不知道手动输入的记录。
找到主键的最大值:
然后将基础序列的下一个值设置为大于该值的数字:
您将找到序列的名称(上面提到的
)使用: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:
Then set the next value of the underlying sequence to a number greater than that:
You'll find the name of the sequence (mentioned above as
<primary_key_seq>
) using: