Skip to content
Advertisement

Use Serializer Method Field in another Method field

In my serializer, I have a method field, that I would want to use in another method field. This will be best explained in code:

class ExampleSerializer(serializers.ModelSerializer):
    data = serializers.CharField()
    analyzed_data = serializers.SerializerMethodField()
    analyzed_analyzed_data = serializers.SerializerMethodField()

    class Meta:
        model = DataProviderModel
        fields = ["data", "analyzed_data", "analyzed_analyzed_data"]

    def get_analyzed_data(self, data):
        return data.capitalize()
    
    def get_analyzed_analyzed_data(self,  analyzed_data):
        return analyzed_data.strip()

serializers.py

class DataProviderModel(models.Model):
    data = models.TextField()

models.py

So I want users to see the first step of data analysis and then analyze the same data further. Is that possible? Maybe that is something I shouldn’t do?

Advertisement

Answer

I would use the to_reprensentation() approach to edit the values from instance.

.to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.

In other words, you can use the to_representation() method to even add values that does not even exists into the fields from the model. Like if you want to add another field to it like "apple":5 you can, although it does not exist in the self.Meta.model.

Therefore, I took the freedom to tailor the answer like this as I do normally. Like this you have much more freedom to do whatever you want with the data without many validations from the framework.

class ExampleSerializer(serializers.ModelSerializer):

    class Meta:
        model = DataProviderModel
        fields = "__all__"

    def analyze_data(self, data):
        # do all things needed here.
        return analyzed_data

    def analyze_analyzed_data(self, analyzed_data):
        # do all things needed here.
        return analyzed_analyzed_data
     
    def to_representation(self, instance):

        analyzed_data = self.analyzed_data(instance.data)
        analyzed_analyzed_data = self.analyzed_analyzed_data(analyzed_data)

        data = {
                "data": instance.data,
                "analyzed_data": analyzed_data,
                "analyzed_analyzed_data": analyzed_analyzed_data
                }

         return data

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement