#Optional model fields

10 messages · Page 1 of 1 (latest)

coral wren
#

Is blank=True enough to make any field optional? Do I need to add null=True along with it?

blazing carbon
#

blank=True is only for CharFields, causing them to store an empty string instead of NULL; you should use null=True for all optional fields

coral wren
#

okay thanks!

blazing carbon
#

Basically:

  • null=True allows the database to store NULL in that field
  • blank=True tells Django to actually store a blank string instead of a NULL for a CharField, so you don't end up with two possible options for an "empty" value in the database
coral wren
#

can I use null instead of blank for Charfield to make my queries simpler? I wouldn't have to make separate conditions to check for null and blank

blazing carbon
#

That was the intention of blank=True, to force everything for that field to be "" instead of NULL, so your queries are simpler. But that actually only applies to the Django Admin, so it's still possible to create objects with NULL outside of that. There's some info here about it with regards to string-based fields specifically: https://docs.djangoproject.com/en/5.1/ref/models/fields/#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. 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.

gilded saddle
#

Isnt blank more of a form thing? It doesnt actually let you save blank, it disables the form validation for being blank and allows the default blank value to be current value. For some fields, json field for example, having null false and blank true ends up with an error because the field doesnt have a default blank value

#

If you have a null true blank false field, admin doesnt allow you to save it empty because it doesn't pass the validation

blazing carbon
#

Yes, it's a form thing