我正在尝试使用循环依赖来复制Peewee示例应用程序,如the docs中所述,尽管创建者明确指出这通常是个坏主意。这是主要从文档复制的代码:
from peewee import *
db = SqliteDatabase(None)
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField()
# Tweet has not been defined yet so use the deferred reference.
favorite_tweet = DeferredForeignKey('Tweet', null=True)
class Tweet(BaseModel):
message = TextField()
user = ForeignKeyField(User, backref='tweets')
db.init('twitter.db')
db.create_tables([User, Tweet])
User._schema.create_foreign_key(User.favorite_tweet) #Error
db.close()
我在用#Error注释的行中得到了一个异常。如文档中所述,此行是必需的:
当您调用create_table时,我们将再次遇到相同的问题。对于 因此,peewee不会自动创建外键 任何延迟的外键的约束。
要创建表和外键约束,可以使用 SchemaManager.create_foreign_key()方法创建约束 在创建表之后。
这是我使用Python 3.5.2的例外情况:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 2653, in execute_sql
cursor.execute(sql, params or ())
sqlite3.OperationalError: near "CONSTRAINT": syntax error
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test3.py", line 23, in <module>
User._schema.create_foreign_key(User.favorite_tweet)
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 4930, in create_foreign_key
self.database.execute(self._create_foreign_key(field))
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 2666, in execute
return self.execute_sql(sql, params, commit=commit)
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 2660, in execute_sql
self.commit()
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 2451, in __exit__ reraise(new_type, new_type(*exc_args), traceback)
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 178, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/peewee.py", line 2653, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: near "CONSTRAINT": syntax error
答案 0 :(得分:0)
Sqlite不支持ALTER TABLE ADD CONSTRAINT-因此,当您使用Sqlite时,应省略对create_foreign_key()的附加调用。
文档中有一个明确的注释:
由于SQLite对更改表的支持有限,因此在创建表后不能将外键约束添加到表中。