Reputation: 1619
this is my serializer:
serializer
start_at=serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
end_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
now I want do calculate in serializer, make this end_at - start_at
and give this value to waite_time
how can I do this?
Upvotes: 2
Views: 2564
Reputation: 19912
You can use a SerializerMethodField
for this matter:
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.
You are not providing any details for your class, but this could be for example:
class MySerializer(serializers.ModelSerializer):
start_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
end_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
# .... (any fields)
diff = serializers.SerializerMethodField()
def get_diff(self, obj):
return obj.end_at - obj.start_at
# .... (any meta etc)
You can also specify a custom method name in the SerializerMethodField
otherwise the default is get_<field_name>
.
Upvotes: 5