Django null and empty string

I find that when I insert anything from the form field through the form, it commits it as an empty line. ''

However, when I insert anything from the integer form field through the form, it commits it as [null] .

Is this a good practice? Should the string be null as well in db?

+7
source share
3 answers

This is a good practice. If the strings were null , there would be two ways to have an empty string: null and "" . This gives you several values ​​to check for, which is inefficient and messy.

This is a Django convention , but is good practice in all applications unless you need null mean something other than "" .

+5
source

I think the string should also be NULL, but it depends on your application, see MySQL, is it better to insert NULL or an empty string? .

If you want to keep NULL for an empty field, add null=True to the field in question. See https://docs.djangoproject.com/en/dev/ref/models/fields/#null

+1
source

It depends on the field.empty_strings_allowed attribute.

In some fields, it is redefined to False . But CharField keeps it True , thereby Field._get_default returns an empty string by default - even if blank=True . The only way to get None by default is to have null=True in the field.

So, if you have a field in db that should never be null and not allow spaces to ever fit there, for example. objects.create . You should put self.full_clean() - or another check - in the save model method.

0
source

All Articles