Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework datetime field format

Tags:

I use this field:

ordered_date = serializers.DateTimeField(format="iso-8601", required=False, read_only=True)

and when i go to rest url, i get time:

"ordered_date": "2015-10-22T19:50:08"

but when i serialize date and then send it with GCM push, it adds miliseconds(2015-10-22T19:53:43.777171), how can i fix this, i need only one format to use, not mix with these two.

How can i fix this?

I use this for ios swift app.

like image 974
Mirza Delic Avatar asked Oct 22 '15 17:10

Mirza Delic


People also ask

What is Read_only field in Django?

read_only. Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

What is Default_authentication_classes?

DEFAULT_AUTHENTICATION_CLASSES. A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the request. user or request. auth properties.

What is Serializers SerializerMethodField ()?

SerializerMethodField. This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. Signature: SerializerMethodField(method_name=None)

How do you pass extra context data to Serializers in Django REST framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.


2 Answers

You can specify a format parameter to the ordered_date field having value as a string representing the output format.

ordered_date = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False, read_only=True)

For example:

In [1]: from rest_framework import  serializers

In [2]: from datetime import datetime

In [3]: class XYZSerializer(serializers.Serializer): # define a serializer with a datetime field
   ...:     ordered_date = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S")
   ...:    

In [4]: x = XYZSerializer(data={'ordered_date':datetime.now()})

In [5]: x.is_valid()
Out[5]: True

In [6]: x.data # contains the datetime field in the desired format
Out[6]: OrderedDict([('ordered_date', '2015-10-22T18:17:51')])
like image 84
Rahul Gupta Avatar answered Sep 30 '22 15:09

Rahul Gupta


Thanks to @Red-Tune-84's comment I customize the format of all my datetimefields.

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
    ....
}
like image 45
C.K. Avatar answered Sep 29 '22 15:09

C.K.