Django FloatField with choices does not work properly in ModelSerializer #8586
Replies: 2 comments 1 reply
-
This error occurs because the type allowed by the serializer and the input data type do not match. [ref source] Soultion AOverride class MyModel(models.Model):
MYFIELD_CHOICES = ((0.5, 0.5), (1.0, 1.0), (1.5, 1.5))
myfield = models.FloatField(choices=MYFIELD_CHOICES)
class CustomChoiceField(serializers.ChoiceField):
def to_internal_value(self, data):
# type casting
if isinstance(data, int):
return float(data)
return super().to_internal_value(data)
class MySerializer(serializers.ModelSerializer):
myfield = CustomChoiceField(choices=MyModel.MYFIELD_CHOICES)
class Meta:
model = MyModel
fields = "__all__" Solution BOverride the serializer class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = "__all__"
def to_internal_value(self, data):
value = data.get("myfield")
if isinstance(value, int):
data["myfield"] = float(value)
return super().to_internal_value(data) |
Beta Was this translation helpful? Give feedback.
-
sorry for a late reply... yes, i actually used something like workaround B in the project, however i am still unsure if this should be the behavior of DRF... if you let's say have an integer field
it will just convert the 2 to integer and store it without any errors... why don't we convert to the target type first and only then check for the choice list? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello! Assume the following model:
and a serializer:
Then, if i do a request to the serializer with
{"myfield": 1}
, i get[ErrorDetail(string='"1" is not a valid choice.', code='invalid_choice')]
Is this the expected behavior?
Beta Was this translation helpful? Give feedback.
All reactions