(Django) Allow NULL for certain model filed with blank and null

Xu LIANG
5 min readJan 30, 2019

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
Registered Time is optional

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.

--

--

Xu LIANG

I’m an engineer focusing on NLP and Data Science. I write stuff to repay the engineer community. You can find me on linkedin.com/in/xu-liang-99356891/