在不可为空的模型字段上处理空白('')字符串值的最佳实践是什么? [英] What is best practice for dealing with blank ('') string values on non-nullable model fields?

查看:122
本文介绍了在不可为空的模型字段上处理空白('')字符串值的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django / postgres中,如果您有一个不可为空的字段,仍然可以存储空白的 str ''用于某些字段类型(例如 CharField TextField )。

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).

请注意,我并不是指 blank = False ,它只是确定字段是否以modelForm中的必需呈现。我的意思是一个文字空白字符串值。

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.

例如,考虑一个简单模型,在<$ c $上具有 null = False c> CharField :

For example, consider this simple model that has null=False on a CharField:

class MyModel(models.Model):
    title = models.CharField('title', null=False)

以下内容引发 IntegrityError

MyModel.objects.create(title=None)

以下内容不会创建对象:

Whilst the following does not, and creates the object:

MyModel.objects.create(title='')

将postgres与Django合并会产生意想不到的结果吗?或者它打算/它有什么实际用途?

Is this an unintended consequence of combining postgres with Django, or is it intended / what practical uses does it have?

如果这是意外的,什么是最佳做法?每个具有 null = False CharField TextField 也应该 CheckConstraint ?例如,

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


推荐答案

来自Django文档:

From the Django docs:

https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models。 Field.null

,请避免在基于字符串的字段(例如CharField和TextField)上使用null。如果基于字符串的字段具有null = True,则意味着它具有无数据的两个可能值:NULL和空字符串。在大多数情况下,为无数据设置两个可能的值是多余的; Django约定是使用空字符串,而不是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. "

这是因为存在一个普遍的误解,即’’= NULL,而Django决定采用这种做法。我个人认为这是一个错误的决定,但确实存在。长度为0的字符串仍然是一个值,也是整数= 0。

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.

这篇关于在不可为空的模型字段上处理空白('')字符串值的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆