Reputation: 2965
I try to use DRF serializers to serialize a model object. I find the DatetimeField in object won't output "2015-10-21T09:28:53.769000Z"
of the ISO-8601 format
I lookup DRF document why I can't output ISO-8601 format. According to datetimefield says:
format
- A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python
It means It's default to output iso-8601
format if I never set DATETIME_FORMAT
argument? Not yet, it's still no change.
When I try to write setting of django project as the following:
REST_FRAMEWORK = {
'DATETIME_FORMAT': "iso-8601",
}
or I write in DatetimeField argument as the following:
class UserSerializer(...):
last_login = DatetimeField(format='iso-8601')
class Meta:
model = User
fields = ('email', 'displayname', 'is_active',
'date_joined', 'last_login')
It's still no change again.
Anyone know how to set it?
Upvotes: 15
Views: 22500
Reputation:
If you don't konw what happen and you still don't slove that, I can define a datettime format in setting as the following:
REST_FRAMEWORK = {
'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ",
}
Upvotes: 33
Reputation: 47846
You don't need to define DATETIME_FORMAT
in settings or format
in last_login
field as iso-861
is the default format.
Here is a sample example showing the serialized output of a datetime field in iso-861
format.
In [1]: from rest_framework import serializers
In [2]: from datetime import datetime
In [3]: class SomeSerializer(serializers.Serializer):
....: last_login = serializers.DateTimeField()
....:
In [4]: x = SomeSerializer(data={'last_login':datetime.now()})
In [5]: x.is_valid()
Out[5]: True
In [6]: x.data # representation of 'last_login' will be in iso-8601 formatted string
Out[6]: OrderedDict([('last_login', u'2015-10-22T09:32:02.788611Z')])
Upvotes: 4