get_or_create() and create() with unspecified non-nullable fields

I’m not currently finding anything in the docs specifically addressing this. (I may be missing something obvious here.)

It is somewhat covered in the Field.null docs:

Avoid using null on string-based fields such as CharField and TextField.

and

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 .

From what I understand from what I’m reading, it looks like it’s covered by the code in django.db.models.fields.__init__. The base Field class has a class variable named empty_strings_allowed, which is set True in this class, but set to False in most other non-charfield classes. This variable is used by the _get_default method to determine whether this method returns an empty string or None.

Digging into the git history, it looks like this same basic mechanism has been in place since version 0.95, so it has basically always been this way. You’d have to go all the way back to the original design to try and find out why. (This also appears to pre-date trac, so you’re not likely to find a ticket addressing it.)

1 Like