user2586618
user2586618

Reputation:

How to change format of a duration field value in serializer?

I have a model called Task with field delay which is a duration field.

class Task:
    delay = models.DurationField(timedelta(seconds=0))

and a serializer as below.

class TaskSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ('id', 'delay')

On creation of instance using serializer, I pass data such as {delay: 30} expecting seconds to be passed.

Instance is created as expected. However on retrieval, I get below result.

[
    {
        "delay": "00:00:00.000060",
    },
    {
        "delay": "00:00:00.000050",
    },
    {
        "delay": "00:00:00.000060",
    }
]

I am trying to get delay value in serializer in integer format only. For example:

[
    {
        "delay": 60,
    },
    {
        "delay": 50,
    },
    {
        "delay": 60
    }
]

I am not willing to change field name "delay" in either write or read serializer. How can I achieve the requirement ?

Upvotes: 4

Views: 4657

Answers (2)

juliocesar
juliocesar

Reputation: 5876

I solved it by using a serializer method to customize duration field serialization, so it can return the value wanted in seconds.

Your code should look like this:

class TaskSerializer(serializers.ModelSerializer):
    delay = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = ('id', 'delay')

    def get_delay(self, obj):
        return obj.delay.total_seconds()

NOTE: Maybe you will need to create different serializers classes for create and retrieve objects, since serializer method only work for read only fields

Hope this helps

Upvotes: 6

Johannes Reichard
Johannes Reichard

Reputation: 947

I would guess the integer is interpreted as microseconds and you need to send your seconds as a string

{"delay": "60"}

If you want to send the seconds as integer (in the json) you pbly need to create a custom Field. The easiest way would be to inherit from DurationField() and adapt the behaviour to your needs.

Upvotes: 1

Related Questions