From 835284df6feec7cf0c8f7fd4c8ed5c4d7996e2e9 Mon Sep 17 00:00:00 2001 From: Radoslav Georgiev Date: Wed, 27 Jul 2016 22:15:29 +0300 Subject: [PATCH] Add code example for default and `format=None` --- docs/api-guide/fields.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index edc6cf0ce..4d11b7a43 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -297,6 +297,46 @@ Corresponds to `django.db.models.fields.DateTimeField`. * Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +For example, lets have the following model: + +```python +from django.db import models + + +class Comment(models.Model): + created_at = models.DateTimeField(auto_now_add=True) +``` + +And the following serializers: + +```python +from rest_framework import serializers + + +class CommentSerializerWithDefaultDateTimeField(serializers.Serializer): + created_at = serializers.DateTimeField() + + +class CommentSerializerWithFormatNone(serializers.Serializer): + created_at = serializers.DateTimeField(format=None) +``` + +Now we have the following types: + +```python +import datetime + +c = Comment.objects.create() + +s1 = CommentSerializerWithDefaultDateTimeField(c) +s2 = CommentSerializerWithFormatNone(c) + + +assert type(s1.data['created_at']) is str +assert type(s2.data['created_at']) is datetime.datetime +``` + + #### `DateTimeField` format strings. Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)