1

I want to have serializer with field which can take integer(not floats or any other numeric type!) or string as an input.Is there any way to make it better/more pretty?

class MyField(Field):
    def to_representation(self, value):
        if isinstance(value, int):
            return value
        elif isinstance(value, str):
            return value
        else:
            raise ValidationError('Error')

    def to_internal_value(self, data):
        if isinstance(data, int):
            return data
        elif isinstance(data, str):
            return data
        else:
            raise ValidationError('Error')

class MySerializer(Serializer):
    my_field = MyField()
2
  • What if value is '1.0' (a string), do you accept it as well or not? Commented Nov 18, 2019 at 17:02
  • '1.0' value is not acceptable. Commented Nov 18, 2019 at 17:08

1 Answer 1

5

You may combine the conditions as below:

class MyField(Field):
    def to_representation(self, value):
        if isinstance(value, int):
            return value
        elif isinstance(value, str) and value.isdigit():
            return value
        raise ValidationError('Error')

    def to_internal_value(self, data):
        if isinstance(data, int):
            return data
        elif isinstance(data, str) and data.isdigit():
            return data
        raise ValidationError('Error')

class MySerializer(Serializer):
    my_field = MyField()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.