I’m currently trying to deserialize JSON data to a Django model. This is quite straight forward for most numeric fields, but I have a
DateTime field which is stored as a timestamp in the original JSON.
At first, I thought I should read the timestamp as an
integer and convert it through post-processing. Then, after reading more of the DRF docs, it became evident I needed a custom field. The code is below:
from rest_framework import serializers from datetime import datetime class TimestampField(serializers.DateTimeField): """ Convert a django datetime to/from timestamp. """ def to_representation(self, value): """ Convert the field to its internal representation (aka timestamp) :param value: the DateTime value :return: a UTC timestamp integer """ result = super(TimestampField, self).to_representation(value) return result.timestamp() def to_internal_value(self, value): """ deserialize a timestamp to a DateTime value :param value: the timestamp value :return: a django DateTime value """ converted = datetime.fromtimestamp(float('%s' % value)) return super(TimestampField, self).to_representation(converted)
The idea is that
to_representation converts a
DateTime field into a timestamp value for serialisation and
to_internal_value does exactly the opposite:
to_representation: just gets the
timestamp()value out of the
to_internal_value: converts the timestamp value to a
datetime.fromtimestamp(float('%s' % value))
This is all!