[英]Followup : missing required Charfield in django Modelform is saved as empty string and do not raise an error
[英]missing required Charfield in django is saved as empty string and do not raise an error
如果我嘗試在Django 1.10中保存不完整的模型實例,那么我會期望Django引發錯誤。 似乎並非如此。
models.py:
from django.db import models
class Essai(models.Model):
ch1 = models.CharField(max_length=100, blank=False)
ch2 = models.CharField(max_length=100, blank=False)
因此,我有兩個字段不允許為空(默認行為,Django在MySQL表創建時應用了NOT NULL
限制)。 我希望Django在存儲前未設置任何字段的情況下引發錯誤。
但是,當我創建一個不完整的實例時,數據存儲就很好了:
>>> from test.models import Essai
>>> bouh = Essai()
>>> bouh.ch1 = "some content for ch1"
>>> bouh.save()
>>> bouh.id
9
>>> bouh.ch1
'some content for ch1'
>>> bouh.ch2
''
>>>
我本來希望Django引發錯誤。 如果我將ch2
強制為None
,則會引發錯誤:
>>> bouh = Essai()
>>> bouh.ch1 = "some content for ch1"
>>> bouh.ch2 = None
>>> bouh.save()
Traceback (most recent call last):
(...)
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: test_essai.ch2
>>> bouh.id
>>> bouh.ch1
'some content for ch1'
>>> bouh.ch2
>>>
這是正常行為嗎? 我錯過了什么? 在這種簡單情況下,為什么Django不將錯誤作為默認行為提出?
謝謝你的燈!
EDIT
我得到了一些答復,指出在SQL中空字符串""
不等同於NULL的事實,如Django模型中所述blank = False無效嗎? 但是,如果我們看一下ModelForm的行為,django doc中似乎存在不一致的地方。
用這個,
from django.db import models
class Essai(models.Model):
ch1 = models.CharField(max_length=100)
ch2 = models.CharField(max_length=100)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.