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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With