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

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

问题描述

我已经在离线版本的Django网络应用程序,并经常删除某个ModelX的模型实例。



我已经从管理页面并没有遇到任何问题。该模型只有两个字段:名称和顺序,与其他模型没有其他关系。



新实例给出下一个可用的pk,这是有道理的,当我删除所有的实例,添加一个新的实例产生一个pk = 1,我期望。



将代码在线移动到我的实际数据库我注意到不是这样。我需要更改模型实例,所以我删除它们,但令我惊讶的是,主键保持递增,而不会重新设置为1。



使用Django进入数据库API已经检查,旧的实例已经消失了,但是即使添加新的实例,也会产生一个主键,该主键可以取代最后删除的实例而不是1。



想知道有没有人知道这里可能是什么问题。

解决方案

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



但是您应该意识到这是 行为。 ID唯一标识数据库中的实体。因此,它只应该是一行。如果该行随后被删除,那么你不应该想要一个新行来重新使用该ID:如果你这样做,你会创建一个混淆在现在删除的实体之前有这个ID和新创建的一个被重用。没有必要这样做,你不应该这样做。


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.

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.

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.

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.

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天全站免登陆