Case-insensitive Django field

Sometimes you need to have a model field where case sensitivity is something you need to omit. There is a pretty good chance you will implement it wrong. If you use Postgres database I have an elegant solution for you.

Postgres offers a great extension that comes really handy in our situation. It's called citext (Case Insensitive text). This field works just like a normal text field but once compared with another text both are converted to lowercase. This means you don't have to take case of case sensitivity at all.

What's even better is that Django comes with an implementation for case-insensitive fields. Following fields can substitude your current fields:

  • CIText
  • CICharField
  • CIEmailField
  • CITextField

you ask database with filter() ORM function don't have to care about case sensitivity. What's even better when you have an unique index (uniq=True) you be sure that data in the field are perfectly case-insensitive . Typical use-case is email field for your users. Once your signs-up with my.cool@email.com addres he can sign-in with My.Cool@Email.com. In the same time he tries to re-sign-up with any variant of that email in terms lower/upper letters he cannot - the email is already registered.