gulden
gulden

Reputation: 585

Django model Field default=None useful?

In my current project I'm working on we use default=None on model Fields, for models.CharField(default=''). Does this make any sense? I looked into the Django documentation, but couldn't find an answer. I searched the Django source code and for models Field the initial is set to default=NOT_PROVIDED and this is defined as

class NOT_PROVIDED:
    pass

so I'm even more confused now. Running my tests in the Django project I had the feeling, that it does not really matter if I used default=None or default=''

Upvotes: 0

Views: 3031

Answers (2)

iklinac
iklinac

Reputation: 15738

As documented

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. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

Upvotes: 1

HuLu ViCa
HuLu ViCa

Reputation: 5452

Well, the difference depends on the use you are going to make of that specific data. For most cases, there is no difference, but you must have clear that '' and None are different Python data types:

>>> type('')
<class 'str'>
>>> type(None)
<class 'NoneType'>
>>>

So there would be a difference when the data type is transcendent in the use context of the data.

Upvotes: 2

Related Questions