Thinking CharField? You'll think again after this

codereviewdoctor

Code Review Doctor

Posted on November 4, 2020

Thinking CharField? You'll think again after this

During my career as a Django code improvement bot I've seen many times when CharField should really have been a TextField:

Using a TextField can be is simpler and less noisy for the reader. I automatically suggested the fix that can be committed with one click.

Given a user need to enter a string and that string may be very long then it's quick and easy to use CharField(max_length=5001), but that has some problems:

  • It's big, but is it big enough? What if the a user wants more? Yes max_length can be increased, but bug fixes are a pain, as is the database migration to facilitate the change.
  • A developer years from now dusts off your code and reads the number 5001. Do they infer there's something special about 5001? Maybe. Devs in the future will be very busy so let's not add ambiguity when maintaining your "old" code.

TextField is better here as there's really no need for a length check, so users will not be presented with a validation error. A nice rule of thumb cane be if the field does not need minimum length check then it probably does not need a maximum length check.

That being said, if TextField is so great, why does CharField exist?

Historically efficient database space usage was a key consideration. But now storage is practically free. Plus, for Postgres at least, using TextField has the same performance as CharField, so database storage performance is not a key consideration.

There are valid cases for CharField with a huge length though: just like an ISBN is always 10 or 13 characters, there are some very long codes. Storing QR codes? CharField. Working with geometry and geo spacial? CharField. Django GIS has a 2048 long VARCHAR that Django represents as a CharField(max_length=2048).

Does your codebase have this problem?

I can check that for you at django.doctor, or can review your GitHub PRs:

Alt Text

Or try out Django refactor challenges.

💖 💪 🙅 🚩
codereviewdoctor
Code Review Doctor

Posted on November 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related