简体   繁体   中英

Renaming DRF serializer fields

I'm using DRF serializers to validate incoming data that I retrieve from a JSON API. I'm trying to rename some awkwardly named fields from the response, making it easier to use the serializer.data further on in my code.

Data received from the API looks like this:

{"FunnyNamedField": true, "AnotherWeirdField": false}

And handling code:

resp = requests.get([...])
resp.raise_for_status()
ser = MyFunnyDataSerializer(data=resp.json())
if ser.is_valid():
    do_domething_with(ser.data)

I would like the serializer to translate the incoming field names to something more consise. ser.data could look like: {'funny': True, 'weird': False} .

What I tried but doesn't work as I hoped:

class MyFunnyDataSerializer(serializers.Serializer):
    funny = serializers.Booleanfield(source='FunnyNamedField')

Is there any way to achieve this without reverting to a SerializerMethodField ?

You can override BaseSerializer to achieve this:

from rest_framework import serializers

class CustomSerializer(serializers.BaseSerializer):

    def to_representation(self, instance):
        return {
            <datas>
        }

You can do some specific modifications on instance serialization with custom methods.

Another solution could be to write your own validator for one field: Field Validator Method .

So in this documentation example you could modify value before return it.

from rest_framework import serializers

class BlogPostSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=100)
    content = serializers.CharField()

    def validate_title(self, value):
        """
        Check that the blog post is about Django.
        """
        if 'django' not in value.lower():
            raise serializers.ValidationError("Blog post is not about Django")
        if value == "something":
            value = "something_else"
        return value

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM