Django测试不会引发CharField的完整性错误 [英] Django tests don't raise integrity error for CharField
问题描述
如果有以下Django(1.4)模型:
If have the following Django (1.4) model:
from django.db import models
class SimpleModel(models.Model):
name = models.CharField(max_length=100)
这个简单的测试:
from django.test import TestCase
from models import SimpleModel
from django.db import IntegrityError
class SimpleTest(TestCase):
def test_integrity_error(self):
with self.assertRaises(IntegrityError):
m = SimpleModel()
m.save()
作为数据库,使用sqlite3数据库。如果我现在使用 python manage.py test< appname>
运行测试,则测试失败, AssertionError:IntegrityError not raise
。
As database a sqlite3 database is used. If I now run the tests with python manage.py test <appname>
the test fails with AssertionError: IntegrityError not raised
.
问题是:为什么?
据我所知(或者想了解)Django的默认值为 blank = False
和 null = False
所以我会假设保存一个默认值的模型实例(我认为一个CharField应该是一个空字符串)肯定会失败!那么为什么不这样呢?
As far as I understand (or thought to understand) Django the default values for Fields are blank=False
and null=False
so I would assume that saving an model instance with the default value (which I think for a CharField should be an empty string) should certainly fail! So, why doesn't this happen?
推荐答案
Django从来没有为空的 CharField
或 TextField
类型。它存储一个空字符串(''
)。所以这就是为什么你没有得到 IntegrityError
for null = False
。
Django never stores NULL for empty CharField
or TextField
types. It stores an empty string (''
). So that's why you don't get an IntegrityError
for null=False
.
对于 blank = False
,只影响表单。它只是使该表单设置为 required = True
,因此除非它有一个值,否则它将不会被验证。它不影响数据库或者您可以在表单之外手动设置空值。
As for blank=False
, that only affects forms. It just makes the form set the field as required=True
so it won't validate unless it has a value. It doesn't affect the database or your ability to manually set a blank value outside of a form.
这篇关于Django测试不会引发CharField的完整性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!