Convert value from datetime to unixtime and unixtime to datetime while serialization and desiarization

22 views
Skip to first unread message

Alexey Polyusov

unread,
Jan 1, 2016, 10:24:17 AM1/1/16
to Django REST framework
Hey guys, I have a JSON with unixtime in it. My Django database has datetime fields. I want JSON unixtime fields to be converted into datetime and inserted into database on POST request.
When doing GET, I want  datetime fields to be converted into JSON with unixtime in it.
How I should perform such things.

class MySerializer(serializers.Serializer):
    
    datecreated = serializers.SerializerMethodField()


    
def get_datecreated(self, obj):
        return datetime.fromtimestamp(obj.dateCreated)


This is what I've done so far. It allows you to convert datetime Django field into unixtime and then into JSON.
How to do the opposite?
What approach should I use?
I've heard about this methods but it's to complicated to ovveride the whole representation while I need only I field to be converted. 
 def to_representation(self, obj):
 def to_internal_value(self, data):

Nacharov Mikhail

unread,
Jan 22, 2016, 4:59:01 AM1/22/16
to Django REST framework

Hi Alexey,

As I understood you need to implement custom field and specify it in your serializer like so:
class UnixTimeField(serializers.Field):
   
def to_representation(self, obj):
       
return calendar.timegm(obj.timetuple())

   
def to_internal_value(self, data):
       
return
datetime.utcfromtimestamp(int(data))

class MySerializer(serializer.Serializer):
datecreated = UnixTimeField()


Also, Thank you for point me out SerializerMethodField in action! This is what I was looking for in this group right now.

 
пятница, 1 января 2016 г., 20:24:17 UTC+5 пользователь Alexey Polyusov написал:
Reply all
Reply to author
Forward
0 new messages