I am trying to understand why this is happening. I have a Django DateTime field and Django Rest Framework serializer that uses the field.
I am trying to compare the dates for both of them and get the following results from JSON endpoint and model result:
DRF: 2018-12-21T19:17:59.353368Z
Model field: 2018-12-21T19:17:59.353368+00:00
Is there a way to make them similar? So, either to make both of them be "Z" or "+00:00."
DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.
The serializers in REST framework work very similarly to Django's Form and ModelForm classes. The two major serializers that are most popularly used are ModelSerializer and HyperLinkedModelSerialzer.
This article revolves around Date and time Fields in Serializers in Django REST Framework. There are four major fields – DateTimeField, DateField, TimeField and DurationField. DateTimeField is a serializer field used for date and time representation.
It is same as – DateTimeField – Django Models 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.
So, borrowing from @RezaTorkamanAhmadi's answer, for anyone looking to get a DRF serializer DateTimeField to have the format 2018-12-21T19:17:59.353368+00:00 (the same format as the default models.DateTimeField so that your serialized values match your model values -- the OP's question and mine too) you're looking for either:
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, date, etc.
It's because django rest framework uses it's own datetime formating. To change that, in your settings.py
file, there should exist a dict variable called REST_FRAMEWORK
(if not create it) and add this:
REST_FRAMEWORK = {
...
'DATETIME_FORMAT': "%Y-%m-%d - %H:%M:%S",
...
}
Also check USE_TZ
variable state too in your settings.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With