Search code examples
djangopostgresqldjango-rest-frameworklogicdjango-serializer

Write if else logic before creating api in serializer DRF


I need to write if else logic to show text alongside my values.before using get method.

models.py

class AnalysisResult(models.Model):
    user_id=models.IntegerField(primary_key=True)
    E=models.IntegerField()
    A=models.IntegerField()
    C=models.IntegerField()
    N=models.IntegerField()
    O=models.IntegerField()
    total=models.IntegerField()
    class Meta:
        db_table='analysis_result'
        
    def __str__(self):
        return self.response

using DRF and serializer I have created api for this model.my created api looks like this when i hit url .

[
    {
        "user_id": 1,
        "E": 25,
        "A": 14,
        "C": 14,
        "N": 38,
        "O": 8,
        "total": 99
    }
]

but now i want to show some text based on the value of individual E,A,C,N,O. my api should look something like this

[
    {
        "user_id": 1,
        "E": 25,
        "A": 14,
        "C": 14,
        "N": 38,
        "O": 8,
        "total": 99,
        "E_Text":"some text",
        "A_Text":"some text",
        "C_Text":"some text",
        "N_text":"some text",
        "O_text":"some text",
         
    }
]

this texts vary with different values of E,A,C,N,O

how can i achieve this task i am not understanding.Please give me a lead.

serailizer.py

class AnalysisResultSerializer(serializers.ModelSerializer):
    
    class Meta:
        model=AnalysisResult
        fields='__all__'

views.py

@api_view(['GET'])
def AnalysisResultInfo(request,user_id):
    if request.method == 'GET':
        Results=AnalysisResult.objects.filter(pk=user_id)
        serializer=AnalysisResultSerializer(Results, many=True)
        return Response(serializer.data)

urls.py

path('Results/<int:user_id>/',views.AnalysisResultInfo)

I dont want to store all these texts in database . i have an idea in mind this can be done using SerializerMethodField(). i just dont know how .


Solution

  • Use SerializerMethodField

    class AnalysisResultSerializer(serializers.ModelSerializer):
        E_Text = serializers.SerializerMethodField()
        A_Text = serializers.SerializerMethodField()
        C_Text = serializers.SerializerMethodField()
        N_Text = serializers.SerializerMethodField()
        O_Text = serializers.SerializerMethodField()
        
        class Meta:
            model=AnalysisResult
            fields='__all__'
        
        def get_E_Text(self, obj):
            # get your in obj and do the math
            return "String you wanted"
    
        # Do same for all other fields