Issue
I am using Field level Validation
in my serializer and I have situation where I need value of first field while validating second field. I know in object level validation
I can have access to that but my serailzer have many=True
and in object level validation I cannot tell client side which iteration have raised the error.
Serailzer :
class Keys_Serializer(serializers.Serializer):
"""
"""
key_id = serializers.IntegerField(required=True)
key_name = serializers.CharField(required=True)
value_id = serializers.IntegerField(required=False)
def validate_key_id(self, value):
"""
validate key id
"""
*** validate key_id here ***
return value
def validate_value_id(self, value):
"""
validate value_id w.r.t key_id
"""
*** I need key_id of current iteration here so that I can validate value_id. ***
return value
Is there any way of accessing the value of key_id in value_id validation.
Solution
No that is not possible. If you need to access more than one value you have to use the Object-level validation
(see docs):
class Keys_Serializer(serializers.Serializer):
key_id = serializers.IntegerField(required=True)
key_name = serializers.CharField(required=True)
value_id = serializers.IntegerField(required=False)
def validate(self, data):
# here you can access all values
key_id = data['key_id']
value_id = data['value_id']
# perform you validation
if key_id != value_id:
raise serializers.ValidationError("key_id must be equal to value_id")
return data
Answered By - ilse2005
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.