Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - How to add or remove fields from a serializer based on a condition?

I'm creating a simple Todo app and I want to provide an api for it. A todo task maybe completed or not. if it's not completed yet, then the field Todo.date_completed will be null.

I want to let the same serializer send the field date_completed if it's not null. One solution would be to let date_created be a SerializerMethodField and send some string like "Not completed yet" in case it's not completed. But that's not really helpful since the client will be asking for the tasks that're not completed anyways...

Another solution would be like here, I've rewritten the same class (Meta) twice just to remove the value

from rest_framework import serializers
from todo.models import Todo


class TodosSerializer(serializers.ModelSerializer):
    date_created = serializers.ReadOnlyField()
    date_completed = serializers.ReadOnlyField()

    class Meta:
        model = Todo
        fields = ['title', 'memo', 'date_created', 'date_completed', 'is_important']


class PendingTodosSerializer(TodosSerializer):

    class Meta:
        model = Todo
        fields = ['title', 'memo', 'date_created', 'is_important']

How to let the field date_completed be sent only in case it's not null?

And one extra question, in case there is no way, can I somehow remove the field date_completed from PendingTodosSSerializer.Meta without rewriting the entire class again so that I don't have to copy and paste the code?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can override the to_representation method of serializer like following

class TodosSerializer(serializers.ModelSerializer):
    date_created = serializers.ReadOnlyField()
    # date_completed = serializers.ReadOnlyField() --remove this

    class Meta:
        model = Todo
        fields = ['title', 'memo', 'date_created', 'is_important'] # also 'date_completed',

   def to_representation(self, instance):
       ret = super(TodosSerializer, self).to_representation(instance)
       if instance.date_completed:
           ret['date_completed'] = instance.date_completed
        return ret

also look at to_representation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...