Add validation for type of Field.choices arguments
|Reported by:||ellisd23@…||Owned by:||ellisd23|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
If I have a model like so:
class Program(models.Model): STATUS_CHOICES = ( (1, 'Inactive'), (2, 'Active'), ) status = models.CharField(choices=STATUS_CHOICES)
And I try get_status_display(), I will get '1' or '2' as the output rather than 'Inactive' or 'Active'. Django silently coerces the type of the choices upon saving, but does not give an indicator upon retrieval that the choice was not found. _get_FIELD_display in db/models/base.py attempts to pull the value from the choices, but since python does not see int and str keys as equivalent, it does not find the value; instead, it defaults to the value in the database.
The end-user solution is to make sure all types are correct, but this could cause confusion for a newbie since this is all done without warning.
I see a few possible solutions:
1) warn the user when creating a choice field that is not of the same type as the model.
2) warn the user when get_FOO_display is called but no value is found.
3) coerce the keys to strings before attempting to retrieve in get_FOO_display. I'm not sure if this would have other implications.
Change History (13)
comment:1 Changed 22 months ago by ellisd23@…
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Type changed from Uncategorized to Bug
comment:3 Changed 22 months ago by ellisd23
- Owner changed from nobody to ellisd23
- Status changed from new to assigned
comment:6 Changed 22 months ago by ptone
- Patch needs improvement set
- Version changed from 1.5 to master