bigjason / django-choices

Sanity to the django choices functionality.
MIT License
175 stars 23 forks source link

Reduce boilerplate with custom ChoiceField #34

Closed ffigiel closed 8 years ago

ffigiel commented 8 years ago

The readme suggests this usage:

type = models.CharField(max_length=1,
                            choices=PersonType.choices,
                            validators=[PersonType.validator])

However, we could provide default behavior with a custom CharField:

(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

type = ChoiceField(choices=PersonType.choices)
ffigiel commented 8 years ago

Of course this is a case for Choices with string values - numeric values would need to be handled differently

sergei-maertens commented 8 years ago

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.

ffigiel commented 8 years ago

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.

merwok commented 7 years ago

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.

sergei-maertens commented 7 years ago

@merwok thanks for the comment, I've cleaned up the docs a bit in the referenced PR.