Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for unknown max_length in Django?

After having to increase max_length of another field in a model, I've started to wonder: maybe this is not the way?

I'm getting data from an external API, so I can't check what's the maximum length. Let's say that I'm guessing the field can have 100 chars - because it makes sense, but I have no idea if this is actually the case, there might appear a value which is 300 chars long. What's the recommended approach here?

1) Truncate the value (where should I put the code then? and what with fields such as URL, which won't work after truncating?)? 2) Skip the value? 3) Set length of every field to 100*expected length?

like image 419
MKaras Avatar asked Jan 02 '23 01:01

MKaras


1 Answers

The point of max_length is that you decide it. If you really want variable/unlimited length text, use TextField instead.

The max_length is enforced on database level, If it's longer, it will just fail. If you want to truncate it from code side, you have to do it yourself, most likely in the function where you create the entry.

Note that, many databases optimize text fields, so there's no penalty in performance for varying length text.

like image 164
blue_note Avatar answered Jan 04 '23 13:01

blue_note