Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model DateTimeField set auto_now_add format or modify the serializer

I have this field in my model:

createdTime = models.DateTimeField(_('Creation date'), help_text=_('Date of the creation'),
                                   auto_now_add=True, blank=True)

And it is saved with this format:

2016-05-18T15:37:36.993048Z

So I would like to convert it to this format DATE_INPUT_FORMATS = ('%d-%m-%Y %H:%M:S') but I dont know where to do it.

I have a simple serializer class, could I override it to modify the format? or maybe create a get_date() model method?

class ObjectSerializer(serializers.ModelSerializer):
    """
    Serializer for object.
    """
    class Meta:
        model = Object

My settings:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S'

USE_I18N = True

USE_L10N = False

USE_TZ = False
like image 628
lapinkoira Avatar asked May 20 '16 12:05

lapinkoira


People also ask

What is difference between Auto_now and Auto_now_add?

From django docs: “”" auto_now Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it's not just a default value that you can override. auto_now_add Automatically set the field to now when the object is first created.

What is meta class in Django model?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.


2 Answers

Set DATETIME_FORMAT in your settings.py as specified here.

The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead

The date part of your settings.py should afterwards look like so:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S' 
USE_L10N = False
USE_TZ = False # if you plan to disable timezone support

Alternatively, you can manually change formats after retrieval by doing:

import datetime

datetime_str = '2016-05-18T15:37:36.993048Z'
old_format = '%Y-%m-%dT%H:%M:%S.%fZ'
new_format = '%d-%m-%Y %H:%M:%S'

new_datetime_str = datetime.datetime.strptime(datetime_str, old_format).strftime(new_format)
print(new_datetime_str)
#'18-05-2016 15:37:36'

This conversion can be added to your serializer or model as your proposed get_date() method

like image 108
Moses Koledoye Avatar answered Sep 28 '22 17:09

Moses Koledoye


You can define the format of your DateTimeField in the serializer of the model (checked on django 3.1.5):

class ObjectSerializer(serializers.ModelSerializer):
   createdTime = serializers.DateTimeField(format="%d-%m-%Y %H:%M:%S")

   class Meta:
      model = Object
      fields = '__all__'
like image 31
Evgeny Umansky Avatar answered Sep 28 '22 18:09

Evgeny Umansky