python - 如何防止 django 数据库将已删除对象的 id 用于新对象?

标签 python database django sqlite django-database

我正在使用 sqlite 数据库编写一个 django 网站,我的网站中有一个如下所示的模型:

class Foo(models.model):
   name = models.Charfield(max_length=30)

数据库为该类创建一个唯一的 Id 列,假设我从类 Foo 创建一个对象,然后将其删除并创建另一个对象 g ,他们的Id是相同的:

>> f = Foo.objects.create(name="fooname")
>> f.id
4
>> f.delete()
>> g = Foo.objects.create(name="fooname2")
>> g.id
4

但我不希望数据库将旧的已删除对象的 id 用于新创建的对象,我该怎么做?

最佳答案

这是一个已知错误,为 fixed在 Django 1.7 中,请参阅:

引自release notes :

AutoField columns in SQLite databases will now be created using the AUTOINCREMENT option, which guarantees monotonic increments. This will cause primary key numbering behavior to change on SQLite, becoming consistent with most other SQL databases. This will only apply to newly created tables. If you have a database created with an older version of Django, you will need to migrate it to take advantage of this feature.

关于python - 如何防止 django 数据库将已删除对象的 id 用于新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23967183/

相关文章:

python - 将 numpy 数组堆叠到对角线上

mysql - 如何在1000亿条帖子中搜索关键字?

c# - 文档库中的 UWP App SQLite Access 数据库

表单操作中的 Django url 重定向

python - Django 模板未呈现

django - 预构建的 Django 项目在迁移时出错

python - 从特定 xml 节点提取值

Mac OS 上的 Python ioctl 错误

php - 这是我的 laravel 项目中的一个额外的 ")",它为我查询 laravel

python - python csv模块如何理解行尾与换行符