为什么我不能在编辑后保存我的模型实例?

时间:2011-06-01 13:33:04

标签: django django-models django-orm django-mptt

我有一个可以实例化的模型,但是一旦创建,如果我尝试保存它,我会得到一个IntegrityError,说主键必须是唯一的。造成这种情况的原因是什么?

还有其他模型继承自Node,他们给了我同样的问题。

这是我的模特:

class Node(MPTTModel):
    title = models.CharField(max_length=255)
    parent = models.ForeignKey('self', null=True, blank=True,
                               related_name='children')

class Book(Node):
    isbn13 = models.CharField(max_length=14)
    description = models.TextField()

这是它生成的SQL:

CREATE TABLE "main_node" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(255) NOT NULL,
    "parent_id" integer,
    "type" varchar(1) NOT NULL,
    "lft" integer unsigned NOT NULL,
    "rght" integer unsigned NOT NULL,
    "tree_id" integer unsigned NOT NULL,
    "level" integer unsigned NOT NULL
)
;
CREATE TABLE "main_book" (
    "node_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "main_node" ("id"),
    "isbn13" varchar(14) NOT NULL,
    "description" text NOT NULL
)
;

当我尝试保存预先存在的模型实例时会发生什么:

>>> b = Book.objects.create(title='c+ for dummies', isbn13='111-1111111111', description='nt')
>>> b.title='c++ for dummies'
>>> b.save()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\Jackie\Desktop\Code\ProjectName\main\models.py", line 56, in save
    super(Book, self).save(self, *args)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 460, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 553, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1436, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 791, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 735, in execute_sql
    cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\util.py", line 34, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 234, in execute
    return Database.Cursor.execute(self, query, params)
IntegrityError: PRIMARY KEY must be unique

以下是运行的查询:

>>> for q in connection.queries:
...   print q['sql'] + "\n\n"
...
SELECT MAX("main_node"."tree_id") AS "tree_id__max" FROM "main_node"


INSERT INTO "main_node" ("title", "parent_id", "type", "lft", "rght", "tree_id", "level") VALUES (c+
 for dummies, None, B, 1, 2, 1, 0)


INSERT INTO "main_book" ("node_ptr_id", "isbn13", "description") VALUES (1, 111-1111111111, nt)




SELECT (1) AS "a" FROM "main_node" WHERE "main_node"."id" = 1  LIMIT 1


UPDATE "main_node" SET "title" = c++ for dummies, "parent_id" = NULL, "type" = B, "lft" = 1, "rght"
= 2, "tree_id" = 1, "level" = 0 WHERE "main_node"."id" = 1


INSERT INTO "main_book" ("node_ptr_id", "isbn13", "description") VALUES (1, 111-1111111111, nt)

为什么在我重新保存已创建的实例时尝试插入main_book?

4 个答案:

答案 0 :(得分:4)

你是否在你的任何模特中超越了“save()”方法?我有一个类似的问题,经过大量的挖掘,发现这是因为我过度使用的“保存()”中的一个小错误。

您能否发布整个模型定义? (从生成的SQL中,看起来你发布的内容并不完整)

答案 1 :(得分:2)

我无法回答为什么你的情况不起作用,但我可以建议一个解决方法。

我对MPTT并不熟悉,但这是否有效还是会导致同样的问题?

b = Book(title='C+ for Dummies', isbn13='111-1111111111')
b.save()
b.title = "C++ for Dummies"
b.save()

答案 2 :(得分:1)

您必须对数据库有一些您不知道的唯一约束,或者您的数据库表的自动递增计数器已重置为某个无效的值。

此链接似乎很有价值: http://old.nabble.com/Reset-auto-increment---truncate-td16494119.html

这样考虑,自动增量计数器正在为已经存在的主键选取值,因为计数器的值设置得低于表中最后一个条目的值,所以当它选择下一个值时,它选择一个已存在的值。

更新:有些奇怪的事情正在发生。从您问题中的SQL查询中,它似乎再次尝试INSERT。尝试:

b.save(force_update=True)

这个特殊情况似乎保证force_update=True,但可能是MPTT或Django代码中的错误。

答案 3 :(得分:1)

尝试比较以下对象,看看是否可以找到任何差异:

b = Book(title='C+ for Dummies', isbn13='111-1111111111')

b = Book.objects.create(title='c+ for dummies', isbn13='111-1111111111', description='nt')