0

I want to send all the data in a response as string, like in database id is stored as integers but I want to send it as string in response. eg: I have the response as

{
"categories": [
    {
        "id": 1,
        "category": "xya",
        "quantity": 25
    }
  ]
}

I want it to be as:

{
"categories": [
    {
        "id": "1",
        "category": "xya",
        "quantity": "25"
    }
  ]
}

I am using ModelSerializer to send all the fields.

2 Answers 2

2

Another option is to convert int to str using the to_representation method of your model serializer.

class YourSerializer(serializers.ModelSerializer):
    # other fields    

    def to_representation(self, instance):
        """ Override `to_representation` method """
        repr = super().to_representation(instance)
        repr['id'] = str(repr['id'])
        repr['quantity'] = str(repr['quantity'])    
        return repr
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I used a loop to change every value, worked for me
0

You can explicitly define id field in your serializer to be CharField()

Like this

class YourSerializer(serializers.ModelSerializer):
    # other fields
    id = serializers.CharField()
    
    class Meta:
        model = SomeModel
        fields = ('id', ..... other fields) 

1 Comment

thanks, actually I had to change every field in a large table, so this method would have been a lot of work, anyways Thanks

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.