删除所有实例后,Django 模型实例主键不会重置为 1 [英] Django model instances primary keys do not reset to 1 after all instances are deleted

查看:37
本文介绍了删除所有实例后,Django 模型实例主键不会重置为 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发 Django Web 应用程序的离线版本,并且经常删除某个 ModelX 的模型实例.

I have been working on an offline version of my Django web app and have frequently deleted model instances for a certain ModelX.

我是从管理页面完成的,没有遇到任何问题.该模型只有两个字段:名称和顺序,与其他模型没有其他关系.

I have done this from the admin page and have experienced no issues. The model only has two fields: name and order and no other relationships to other models.

新实例将获得下一个可用的 pk,这是有意义的,当我删除所有实例时,添加新实例会产生 pk=1,这是我所期望的.

New instances are given the next available pk which makes sense, and when I have deleted all instances, adding a new instance yields a pk=1, which I expect.

将代码在线移动到我的实际数据库中,我注意到情况并非如此.我需要更改模型实例,因此我将它们全部删除,但令我惊讶的是,主键一直在递增,而没有重置回 1.

Moving the code online to my actual database I noticed that this is not the case. I needed to change the model instances so I deleted them all but to my surprise the primary keys kept on incrementing without resetting back to 1.

使用我检查过的 Django API 进入数据库,旧实例消失了,但即使添加新实例也会产生一个主键,该主键从上次删除的实例停止的地方开始,而不是 1.

Going into the database using the Django API I have checked and the old instances are gone, but even adding new instances yield a primary key that picks up where the last deleted instance left off, instead of 1.

想知道是否有人知道这里可能存在什么问题.

Wondering if anyone knows what might be the issue here.

推荐答案

正如其他人所说,这完全是数据库的责任.

As others have stated, this is entirely the responsibility of the database.

但是您应该意识到这是可取的行为.ID 唯一标识数据库中的实体.因此,它应该只引用一行.如果该行随后被删除,则没有理由希望新行重新使用该 ID:如果这样做,则会在现在删除的曾经拥有该 ID 的实体与新创建的一个重用它.这样做没有意义,您不应该想要这样做.

But you should realize that this is the desirable behaviour. An ID uniquely identifies an entity in your database. As such, it should only ever refer to one row. If that row is subsequently deleted, there's no reason why you should want a new row to re-use that ID: if you did that, you'd create a confusion between the now-deleted entity that used to have that ID, and the newly-created one that's reused it. There's no point in doing this and you should not want to do so.

这篇关于删除所有实例后,Django 模型实例主键不会重置为 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆