Closed ffigiel closed 8 years ago
Of course this is a case for Choices with string values - numeric values would need to be handled differently
I think the documentation needs updating, since Django applies a ChoicesValidator by itself as soon as you use the choices
option. Leaving that off would already reduce some boilerplate.
You correctly mention the case where the field is not a CharField - this would require some 'magic' introspection to figure out the 'best fitting' field type.
The same kind of magic where the max_length
is guessed is also only relevant for CharField, and doesn't cover the case where you add an extra choice with a longer max_length
. It would be caught in a migration though, but it's again guessing/magic, and that is against the Zen of Python (https://www.python.org/dev/peps/pep-0020/): In the face of ambiguity, refuse the temptation to guess.
I don't feel that this is a good direction to take.
I didn't know about that validator, thanks!
If you added a new choice, ChoiceField.max_length would be updated and require a migration, which makes sense to me - adding new choices wouldn't require you to manually count characters and update max_length.
Anyway, this field would be simple enough to develop by self in case someone needs it.
I think the documentation needs updating, since Django applies a ChoicesValidator by itself as soon as you use the choices option. Leaving that off would already reduce some boilerplate.
This is still a valid doc change IMHO.
@merwok thanks for the comment, I've cleaned up the docs a bit in the referenced PR.
The readme suggests this usage:
However, we could provide default behavior with a custom CharField:
choices
acceptsDjangoChoices
subclassmax_length
is inferred from max(len(l) for l in GivenChoices.labels)validators
is[GivenChoices.validator]
by default(While most of these are a matter of preference, automatically picking the
max_length
value would surely be an useful feature)Then we can simply do this