You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
MainSerializer(data={"version": "v1"}).is_valid()
#> KeyError: "`MainSerializer.serializer_mapping` is missing a corresponding serializer for the `<class 'rest_framework.fields.empty'>` key"
adds an extra layer of validation, by calling is_valid again on the mapped serializer from the discriminator. However, if the first super().is_valid() call failed, self.validated_data is set to {} by DRF, so drf-polymorphic is unable to retrieve the serializer from the mapping, which leads to the KeyError.
The question now is: why is super().is_valid() failing? In the example, the data provided to MainSerializer seems to comply, at first sight there is no reason for super().is_valid() to fail. The reason is that the DRF implementation of is_valid calls to_internal_value which is overridden in our case:
and calls to_internal_value on the mapped serializer, which will run validation on each field of this serializer.
So it's a bit of a mess, validation is run twice but simply removing the extra logic in is_valid is not enough as we still need to run the mapped serializer validators (as to_internal_value only runs fields validators).
However, I think better exception handling could be applied so that is_valid(raise_exception=False) doesn't raise unexpected errors.
The text was updated successfully, but these errors were encountered:
With the following example:
I get some unusual behaviors when doing:
The
is_valid
override:drf-polymorphic/drf_polymorphic/serializers.py
Lines 90 to 97 in 8166533
adds an extra layer of validation, by calling
is_valid
again on the mapped serializer from the discriminator. However, if the firstsuper().is_valid()
call failed,self.validated_data
is set to{}
by DRF, sodrf-polymorphic
is unable to retrieve the serializer from the mapping, which leads to theKeyError
.The question now is: why is
super().is_valid()
failing? In the example, the data provided toMainSerializer
seems to comply, at first sight there is no reason forsuper().is_valid()
to fail. The reason is that the DRF implementation ofis_valid
callsto_internal_value
which is overridden in our case:drf-polymorphic/drf_polymorphic/serializers.py
Lines 82 to 88 in 8166533
and calls
to_internal_value
on the mapped serializer, which will run validation on each field of this serializer.So it's a bit of a mess, validation is run twice but simply removing the extra logic in
is_valid
is not enough as we still need to run the mapped serializer validators (asto_internal_value
only runs fields validators).However, I think better exception handling could be applied so that
is_valid(raise_exception=False)
doesn't raise unexpected errors.The text was updated successfully, but these errors were encountered: