简体   繁体   English

django中缺少必需的Charfield的字段被保存为空字符串,并且不会引发错误

[英]missing required Charfield in django is saved as empty string and do not raise an error

If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. 如果我尝试在Django 1.10中保存不完整的模型实例,那么我会期望Django引发错误。 It does not seem to be the case. 似乎并非如此。

models.py: 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)

So I have two fields not allowed to be empty (default behavior, NOT NULL restriction is applied by Django at MySQL table creation). 因此,我有两个字段不允许为空(默认行为,Django在MySQL表创建时应用了NOT NULL限制)。 I expect Django to rase an error if one of the fields is not set before storing. 我希望Django在存储前未设置任何字段的情况下引发错误。

However, when I create an incomplete instance, the data is stored just fine: 但是,当我创建一个不完整的实例时,数据存储就很好了:

>>> 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
''
>>> 

I would have expected Django to raise an error. 我本来希望Django引发错误。 If I force ch2 to None , however, it raises an error: 如果我将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
>>>

Is this normal behavior? 这是正常行为吗? Did I miss something? 我错过了什么? Why is Django not raising an error as default behavior in this simple case? 在这种简单情况下,为什么Django不将错误作为默认行为提出?

Thanks for your lights! 谢谢你的灯!

EDIT

I got a few replies pointing out the fact that in SQL empty string "" is not equivalent to NULL, as stated in Django model blank=False does not work? 我得到了一些答复,指出在SQL中空字符串""不等同于NULL的事实,如Django模型中所述blank = False无效吗? However, if we look at ModelForm behavior, there seem to be a inconsistency in django doc. 但是,如果我们看一下ModelForm的行为,django doc中似乎存在不一致的地方。

see question Followup : missing required Charfield in django Modelform is saved as empty string and do not raise an error 请参阅问题跟进:在Django Modelform中缺少必需的Charfield会被保存为空字符串,并且不会引发错误

Use this, 用这个,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM