在某些情况下,Python 模块 Peewee 会在保存对象时重置(非整数)主键。我构建了这个示例来澄清:
#!/usr/bin/python
from peewee import *
import uuid
db = SqliteDatabase('./db/' + str(uuid.uuid4()) + '.db')
class A(Model):
id = CharField(primary_key=True)
def __init__(self):
super(A, self).__init__()
self.id = str(uuid.uuid4())
class Meta:
database = db
class B(A):
name = CharField()
def __init__(self, name):
super(B, self).__init__()
self.name = name
A.create_table()
a = A()
print a.id
a.save(force_insert=True)
print a.id
print "--"
B.create_table()
b = B(name='Test')
print b.id
b.save(force_insert=True)
print b.id
示例输出:
$ ./pkey.py
0bd49fa9-c5cc-40e7-aff7-24e0b17247cb
0bd49fa9-c5cc-40e7-aff7-24e0b17247cb
--
2fe23bac-4cb2-46a2-827a-8a1c6395e665
1
现在,最后一行不应该是 1,而是 2fe...,如上面的行。有趣的是,正如示例所示,这种情况只发生在子对象上。
我是否完全误解了这里的某些内容?
最佳答案
我已在 GitHub 上解决了此问题并发布了修复程序。该问题是由模型之间的主键字段继承中的错误引起的。
关于Python Peewee重置主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15552681/