Add validation for type of Field.choices arguments
|Reported by:||Owned by:||ellisd23|
|Component:||Core (System checks)||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 (14)
comment:1 Changed 3 years ago by
|Patch needs improvement:||unset|
|Type:||Uncategorized → Bug|
comment:13 Changed 3 years ago by
|Summary:||get_FOO_display does not return proper value or warn for inconsistent type → Add validation for type of Field.choices arguments|
|Type:||Bug → New feature|