I need to take a form that has a field "starttime" that is in EPOCH and convert it to
- python datetime
- fieldname = "created"
when I have:
models.py
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True
class Meta:
ordering = ('created',)
serializers.py
import time
class SnippetSerializer(serializers.ModelSerializer):
starttime = serializers.SerializerMethodField('epoch')
def epoch(self, obj):
""" Return epoch time for a datetime object or ``None``"""
try:
return int(time.mktime(obj.created.timetuple()))
except (AttributeError, TypeError):
return None
class Meta:
model = Snippet
fields = ('starttime')
If I:
"GET" /snippets/1/
{"id":1, 'starttime':13232111}
I want to be able to do:
"POST" /snippets/1/ {"id":1, 'starttime':1}
{"id":1, 'starttime':1}
right now, it just ignores the request. I am forced to use unix epoch times to conform to existing API's.
If I understand it correctly, you need to deserialize the
starttime
field and use it's value to updatecreated
field. If that's so, then you need to create your own serializer field and overridefield_from_native
(it doesn't return anything by default, that's why it doesn't have any effect in your case):so the idea is simple, just reverse the calculation to generate
created
value and use your new serializer field. You can also move the content from the epoch method intofield_to_native
method of the new serializer field.Based on Kevin Stone's answer, I've created timezone aware serializer fields, including a
UnixEpochDateField
. The actual conversion methods are static because I've found them useful elsewhere in my code.Please see below code it will help you to solve your problem.
Adapting Kevin Stone code for Django Rest Framework 3:
You want to write your own serializer Field sub-class with overridden
to_native()
andfrom_native()
for the actual conversion. Here's my attempt:And then use that field in your
Serializer
definition: