Thinking CharField? You’ll think again after this
I’m a GitHub bot that checks pull requests and makes Django improvements.
Many times I’ve seen the use of CharField
when TextField
may be better:
TextField
can be is simpler and less noisy for the reader. Notice I automatically suggest the code that can be committed with one click.Say we want users to enter a very long input. It’s easy to muscle memory and reach for CharField(max_length=5001)
, but that has some problems:
- Is 5001 long enough? What if the a user wants to enter more? Sure
max_length
can be increased, but do we really want the hassle of a bug fix deployment and an entire database migration to facilitate this change? - A developer far in the future may read the code and conclude there’s something special about 5001. They have enough on their hands, let’s not add ambiguity when maintaining the code.
TextField
might be better used here as practically there is no need for a max length check, so users will not be presented with a validation error.
That being said, if TextField
is so great, why would we not default to using TextField
always?
Historically we may have looked to database performance such as efficient space usage. However, for Postgres at least, using TextField
has the same performance as CharField
, so database storage performance is not a key consideration.
There are cases when CharField
with a very long value are appropriate 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)
.
You can check your entire codebase at django.doctor or install the GitHub PR bot to reduce dev effort during code review and improve your code with no cost.