(Django) Allow NULL for certain model filed with blank and null
Django model API provides powerful features to let the developer built the model for specific needs. In some cases, we want to let a certain model filed optionally so that the user can submit the form with some blank fields. But things get complicated if we use string-based filed.
In this article, I will use a simple example to show how to set unique but optional for non-string-based filed and string-based filed. The article is structured as follow:
- A Company-Department-Employee Example
- Add an optional filed to non-string-based field
- Set string-base filed optionally
- Django convention for string-based fields
- Solution: change empty string before it is sent to the database
- Advanced usage: unique_together
- Reference
A Company-Department-Employee Example
See we run a company, called Umbrella Corporation. Our company has many departments. A department can have any number of employee, including 0. Each employee has some attributes.