开发者

django null and empty string

I find that when I insert nothing of a string form field through a form it captures it as an empty string ''.

However when I insert nothing of an integer form field through a form it ca开发者_如何学JAVAptures it as [null].

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


It is good practice. If strings were allowed to be null, there would be two ways to have an empty string: null and "". This gives you multiple values to check against, which is inefficient and messy.

This is a Django convention, but is good practice in all applications, unless you have the need for null to mean something different than "".


It depends on the field.empty_strings_allowed attribute.

Some fields have it overridden to False. But CharField keeps it True, thus making Field._get_default return empty string as default — even if blank=True. The only way to get None as default is to have null=True on a field.

So if you have field in db that should never be null and not allow blanks to be never ever put in there by for e.g. objects.create. You need to put self.full_clean() — or other validation — in the model save method.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜