What is best practice for dealing with blank ('') string values on non-nullable model fields?

左心房为你撑大大i 提交于 2020-07-23 07:39:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!