I have a model with a object_type
field where the choices should be numbers and the human readable a string like below:
OBJECT_TYPES = (
(0, "analog-input"),
(1, "analog-output"),
(2, "analog-value")
)
class MyModel(models.Model):
object_type = models.CharField(
max_length=20,
choices=OBJECT_TYPES,
blank=True,
null=True
)
However, when I try to create an object and assign an integer value to object_type I get a ValidationError
that the object_type
is not a valid choice and I can't understand how to configure it properly. I have tried with CharField
, TextField
and IntegerField
.
obj = MyModel.objects.create(object_type=2)
obj.full_clean()
ValidationError: {'object_type': ["Value '2' is not a valid choice."]}
CodePudding user response:
Since this is a CharField
, the keys should be strings, so '0'
, not 0
:
OBJECT_TYPES = (
('0', "analog-input"),
('1', "analog-output"),
('2', "analog-value")
)
an alternative is to work with an IntegerField
:
OBJECT_TYPES = (
(0, "analog-input"),
(1, "analog-output"),
(2, "analog-value")
)
class MyModel(models.Model):
object_type = models.IntegerField(
choices=OBJECT_TYPES,
blank=True,
null=True
)