简体   繁体   中英

Divide Serializer Django rest framework

I have a Serializer receiving:

{
    "suggestions": [
      {
       "description": "Portugal - Porto",       
       "integration_data": {
        .......
         }
      },
     {
      "description": "Portugal - Porto",
      "another_data":{
       .......
      }
     }]
}

How can I make my Serializer do something like: if integration_data is not Null go to function X where I will work with all logic of the serializer if another_data is not Null go to function Y where I will work with all logic of the serializer.

At the moment my serializer is written as:

class SuggestionSerializer(serializers.HyperlinkedModelSerializer):
    integration_data = serializers.DictField(write_only=True, allow_null=True, required=False)
    sponsor_data = serializers.DictField(write_only=True, allow_null=True, required=False)

Thanks

Sounds like you want to use a serializer method field . Something like

class SuggestionSerializer(serializers.HyperlinkedModelSerializer):
    integration_data = = serializers.SerializerMethodField()
    ...
    def get_integration_data(self, obj):
        # Insert logic for generating value of this field here
        ...
        return value

This allows you to arbitrarily generate the value of the field based on logic rather than data.

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