During my career as a Django code improvement bot I've seen many times when
CharField should really have been a
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_lengthcan 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
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
Or try out Django refactor challenges.