我有一个 django 项目,其中的测试在我调用时运行py.test
,但我最近注意到它不检查外键约束。我怎样才能让它检查外键约束?
显然,外键约束直到 sqlite 3 才成为可能 https://sqlite.org/foreignkeys.html,但我真的不知道我正在运行什么版本,因为我没有 sqlite 的 cli,但它只是被 django 自动包含? (我使用的是 django 1.9.10),但是 sqlite 3 于 2009 年发布,所以这不是问题,对吧?
Perhaps 应用程序仍必须在运行时使用 PRAGMAforeign_keys 命令启用它。 https://sqlite.org/foreignkeys.html,但我不知道如何让我的测试做到这一点?
[更新]
所以,看起来开箱即用的 sqlite 没有检查它们。
class Referenced(models.Model):
pass
class Referencer(models.Model):
fk = models.ForeignKey(Referenced)
>>> Referencer.objects.create(fk_id=-1)
<Referencer>
>>> Referencer.objects.all()[0].fk
DoesNotExist
我最终创建了一个包来解决这个问题。
pip install sqlite_checkforeignkeys
然后配置数据库:
DATABASES = {
'default': {
'ENGINE': 'sqlite_checkforeignkeys_engine',
'TEST': {'NAME': ':memory:'},
}
}
它涉及重写现有的 sqlite 引擎以强制执行外键
更多信息请参见https://github.com/hulu/sqlite_checkforeignkeys https://github.com/hulu/sqlite_checkforeignkeys
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)