Salad.Guyo
Salad.Guyo

Reputation: 3395

How to serialize DateTimeField in Django

How can I serialize dob field to achieve dob to be specifically in the format e.g ==> 03/Jan/2020 or 05-Feb-2021

class PersonSerializer():
    ....
    ........
    dob = serializers.DateTimeField(format="%d/%m/%Y")


    class Meta:
        model = Person
        fields = "__all__"

What I have so far is in the format e.g 20/12/2020

Upvotes: 1

Views: 7084

Answers (2)

Amandeep Singh
Amandeep Singh

Reputation: 1431

If you want to output dates in certain format globally then you set it in settings.py file.

settings.py

REST_FRAMEWORK = {
    'DATE_FORMAT': "%d/%m/%Y",
    #-- other settings-----#

}

However if you want to output for a certain field of model only then you can do this.

class PersonSerializer(serializers.ModelSerializer):
    # ....
    # ........
    custom_dob = serializers.ReadOnlyField()

    class Meta:
        model = Person
        fields = "__all__"

You can create property in Person model

class Person(models.Model):
    dob = models.DateField()

    @property
    def custom_dob(self):
        return self.dob.strftime("%d/%m/%Y")

Upvotes: 1

berkeebal
berkeebal

Reputation: 493

From DRF docs;

DateTimeField format strings. Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')

So you can format it like datetime.datetime object. Such as

class PersonSerializer():
    ....
    ........
    dob = serializers.DateTimeField(format="%d/%b/%Y")

    class Meta:
        model = Person
        fields = "__all__"

Also we have to mention that setting to a format string means that to_representation return values should be forced to string output.

Upvotes: 2

Related Questions