问题
In Django/postgres if you have a non-nullable field, it's still possible to store a blank str value '' for certain field types (e.g. CharField, TextField).
Note I am not referring to blank=False, which simply determines if the field is rendered with required in a modelForm. I mean a literal blank string value.
For example, consider this simple model that has null=False on a CharField:
class MyModel(models.Model):
title = models.CharField('title', null=False)
The following throws an IntegrityError:
MyModel.objects.create(title=None)
Whilst the following does not, and creates the object:
MyModel.objects.create(title='')
Is this an unintended consequence of combining postgres with Django, or is it intended / what practical uses does it have?
If it's unintended, what's best practice to deal with this? Should every CharField and TextField with null=False also have a CheckConstraint? E.g.
Class Meta:
constraints = [
models.CheckConstraint(
check=~models.Q(title=''),
name='title_required'
)
]
回答1:
From the Django docs:
https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.Field.null
"Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. "
This is because there is common misconception out there that '' = NULL and Django decided to go with that. I personally think it was a bad decision but there it is. A string of length 0 is still a value as is an integer = 0.
来源:https://stackoverflow.com/questions/62843073/what-is-best-practice-for-dealing-with-blank-string-values-on-non-nullable