简体   繁体   English

重命名DRF序列化器字段

[英]Renaming DRF serializer fields

I'm using DRF serializers to validate incoming data that I retrieve from a JSON API. 我正在使用DRF序列化程序来验证从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. 我正在尝试从响应中重命名一些笨拙的命名字段,以便更轻松地在代码中进一步使用serializer.data

Data received from the API looks like this: 从API接收的数据如下所示:

{"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} . ser.data可能类似于: {'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 ? 有什么方法可以实现而无需恢复为SerializerMethodField

You can override BaseSerializer to achieve this: 您可以重写BaseSerializer来实现此目的:

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 . 另一种解决方案是为一个字段编写自己的验证器: 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. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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