Timestamp to DateTime Serializer Field for DRF

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:

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 DateTime field
  • to_internal_value: converts the timestamp value to a DateTime object via:

This is all!

HTH,


A little experiment: If you find this post and ad below useful, please check the ad out :-)




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top